Answer the question
In order to leave comments, you need to log in
How to use Dagger 2 with Room so that there is only one instance of the database and there are not thousands of additional classes and interfaces?
Entiry
@Entity(tableName = "notes")
public class Note {
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
public long id;
@ColumnInfo(name = "title")
public String title;
@ColumnInfo(name = "content")
public String content;
@ColumnInfo(name = "date")
public String date;
}
@Dao
public interface NoteDao {
@Query("SELECT * FROM notes ORDER BY date DESC")
List<Note> getAll();
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insert(Note note);
@Update
void update(Note note);
@Delete
void delete(Note note);
}
@Database(entities = Note.class, version = 1)
public abstract class AppDatabase extends RoomDatabase {
public abstract NoteDao noteDao();
}
Answer the question
In order to leave comments, you need to log in
What thousands, what are you talking about? One module class, one component interface, and component initialization lines where necessary, and if necessary, then the scope interface ... have you read the dagger documentation at all? Have you looked at standard examples?
private const val databaseName = "knote.db"
@Database(
entities = [Note::class],
version = 4,
exportSchema = false
)
abstract class InnerDb : RoomDatabase() {
abstract fun createNoteDao(): NoteDao
companion object {
fun createInstance(context: Context): InnerDb {
return Room.databaseBuilder(context, InnerDb::class.java, databaseName)
.allowMainThreadQueries()
.fallbackToDestructiveMigration()
.build()
}
}
}
Why do you need Room? open connections directly and work with cursors. As it turns out, you can try Room. ;)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question