我正在尝试使用 Room 和 Dao 实现一个简单的数据库,这就是我所做 的我的实体:
@Entity(tableName = "notes") public class Note implements Serializable { @PrimaryKey(autoGenerate = true) private int id; @ColumnInfo(name = "title") private String title; @ColumnInfo(name = "date_time") private String datetime; @ColumnInfo(name = "subtitle") private String subtitle; @ColumnInfo(name = "note_text") private String noteText; }
我还生成了所有的 getter 和 setter,entity但我不包括在这里,因为它很长。 我的道界面:
entity
@Dao public interface NoteDAO { @Query("SELECT * FROM notes ORDER BY id DESC") List<Note> getAllNotes(); @Insert(onConflict = OnConflictStrategy.REPLACE) void insertNote(Note note); @Delete void deleteNote(Note note); }
我的数据库类:
@Database(entities = Note.class, version = 1, exportSchema = false) public abstract class NoteDatabase extends RoomDatabase { private static NoteDatabase noteDatabase; public static synchronized NoteDatabase getDatabase(Context context){ if (noteDatabase == null){ noteDatabase = Room.databaseBuilder( context, NoteDatabase.class, "note_db" ).build(); } return noteDatabase; } public abstract NoteDAO noteDAO(); }
当我使用List<Note> notesandnotes.toString()时,它只显示日期和时间,标题是null,我还注意到在 中Dao interface,它会引发 2 个错误,即Cannot resolve symbol notesand Cannot resolve symbol id。我不明白为什么它不插入数据库。有人可以帮我解决这个问题吗?谢谢你的帮助 !
List<Note> notes
notes.toString()
null
Dao interface
Cannot resolve symbol notes
Cannot resolve symbol id
您在问题中包含的代码很好(在添加了 getter 和 setter 之后),然后使用:-
public class MainActivity extends AppCompatActivity { NoteDatabase db; NoteDAO dao; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); db = NoteDatabase.getDatabase(this); dao = db.noteDAO(); Note note1 = new Note(); note1.setTitle("NOTE001"); note1.setDatetime("2022-01-01 10:30"); note1.setSubtitle("The First Note"); note1.setWebsite("www.mynotes.com"); note1.setNoteText("This is the note"); note1.setColor("Black"); note1.setImagePath("notes/note1.jpg"); dao.insertNote(note1); for (Note n: dao.getAllNotes()) { Log.d("NOTEINFO","Title is " + n.getTitle() + " Date is " + n.getDatetime() + " blah blah ToString = " + n); } } }
.allowMainThreadQueries
结果是:-
D/NOTEINFO: Title is NOTE001 Date is 2022-01-01 10:30 blah blah ToString = NOTE001 : 2022-01-01 10:30
但是,添加:-
Note note2 = new Note(); //note1.setTitle("NOTE001"); //<<<<<<<<<<< OOOPS note2.setDatetime("2022-01-01 10:30"); note2.setSubtitle("The Second Note"); note2.setWebsite("www.mynotes.com"); note2.setNoteText("This is the note"); note2.setColor("Black"); note2.setImagePath("notes/note2.jpg");
结果您似乎按照以下方式描述:-
D/NOTEINFO: Title is null Date is 2022-01-01 10:30 blah blah ToString = null : 2022-01-01 10:30
我相信你说
我还注意到,在 Dao 界面中,它引发了 2 个错误,即无法解析符号注释和无法解析符号 id
也许是原因的线索,这可能是你有不正确的依赖关系,你应该有 2 个房间:-
implementation 'androidx.room:room-runtime:2.5.0-alpha02'
annotationProcessor 'androidx.room:room-compiler:2.5.0-alpha02'
另一种可能性是,除了 getter 和 setter 之外,您还有一个构造函数未正确设置标题,因此将其保留为空。