C
C
cepprice2019-11-23 14:12:19
Java
cepprice, 2019-11-23 14:12:19

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
@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
@Database(entities = Note.class, version = 1)
public abstract class AppDatabase extends RoomDatabase {
    public abstract NoteDao noteDao();
}

All the solutions that I have seen involve creating thousands of classes and interfaces, is it really possible without this?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
T
tiroman, 2019-11-23
@cepprice

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?

A
Alina Mitrokhina, 2019-11-23
@fursa08

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()
        }
    }
}

M
Maxim Firsov, 2019-11-27
@FirsofMaxim

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 question

Ask a Question

731 491 924 answers to any question