Hi I can’t store values in the database DAO android. I have User.class:
public class User { @PrimaryKey @NonNull public String uid; @ColumnInfo(name="name") public String name; public User(String uid, String name){ this.uid=uid; this.name=name; } }
DAO database:
@Dao public interface UserDAO { @Query("select*from User") List<User> getAll(); @Insert(onConflict = OnConflictStrategy.REPLACE) void insertAll(User users); }
My Dtababase class is:
@Database(entities = {User.class},version=1) public abstract class AppDatabase extends RoomDatabase { public abstract UserDAO userDAO(); }
My code
new Thread(new Runnable() { @Override public void run() { try { AppDatabase db = Room.databaseBuilder(activity.getApplicationContext(), AppDatabase.class, "user_db").build(); UserDAO userDao = db.userDAO(); userDao.insertAll(new User("11","Melany")); Log.d("main_activity_uid", "ok you are pretty"); } catch (Exception e) { e.printStackTrace(); } } }).start();
Now my code don’t store new User(i can’t print “ok you are pretty”).Why? I have another question: i know that when you store data in the database you use threads but what do threads allow you to do?
Advertisement
Answer
A problem is that you always create in a new database instance instead of having a singleton database.
Single instance (source):
private static volatile WordRoomDatabase INSTANCE; static WordRoomDatabase getDatabase(final Context context) { if (INSTANCE == null) { synchronized (WordRoomDatabase.class) { if (INSTANCE == null) { INSTANCE = Room.databaseBuilder(context.getApplicationContext(), WordRoomDatabase.class, "word_database") .build(); } } } return INSTANCE; }
You need a thread because the Room
database does not allow operations on the main thread to prevent blocking the UI (source)