[英]I can't store values in the database DAO android
Hi I can't store values in the database DAO android.嗨,我无法在数据库 DAO android 中存储值。 I have User.class:
我有 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 数据库:
@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?
我还有一个问题:我知道当您将数据存储在数据库中时,您使用线程,但是线程允许您做什么?
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 )您需要一个线程,因为
Room
数据库不允许在主线程上进行操作以防止阻塞 UI( 来源)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.