我已经使用如下简单的 Room 测试代码测试了一些测试用例。主要活动恢复后,“dao.getAll().observeForever()”不起作用。新词插入正确,但只有观察不起作用。如果我使用 dao.getAll().observe(),它总是可以正常工作。不允许在活动的 onCreate() 方法上使用 observeForever 吗?
应用数据库.java
@Database(entities = {Word.class}, version = 2)
public abstract class AppDatabase extends RoomDatabase {
private static AppDatabase sInstance;
public abstract WordDao wordDao();
public static AppDatabase getInstance(Context context) {
if (sInstance == null) {
synchronized (AppDatabase.class) {
if (sInstance == null) {
sInstance = Room.databaseBuilder(context.getApplicationContext(),
AppDatabase.class, "word.db").addMigrations(new Migration(1, 2) {
@Override
public void migrate(@NonNull SupportSQLiteDatabase database) {
}
}).build();
}
}
}
return sInstance;
}
}
Word.java
@Entity
public class Word {
@PrimaryKey(autoGenerate = true)
public int uid;
public String word;
public Word(String word) {
this.word = word;
}
}
WordDao.java
@Dao
public interface WordDao {
@Query("Select * from word")
LiveData<List<Word>> getAll();
@Update
void update(Word word);
@Insert
void insert(Word word);
}
MainActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = findViewById(R.id.textview);
WordDao dao = AppDatabase.getInstance(this).wordDao();
dao.getAll().observeForever(wordlist -> {
StringBuilder builder = new StringBuilder();
for (Word w : wordlist ) {
builder.append(w.word).append(", ");
}
tv.setText(builder.toString());
});
findViewById(R.id.add).setOnClickListener(view -> new Thread(() -> {
dao.insert(new Word("haha"));
}).start());
}
构建.gradle
dependencies {
def lifecycle_version = "1.1.1"
implementation "android.arch.lifecycle:extensions:$lifecycle_version"
implementation "android.arch.lifecycle:common-java8:$lifecycle_version"
testImplementation "android.arch.core:core-testing:$lifecycle_version"
def room_version = "1.1.1"
implementation "android.arch.persistence.room:runtime:$room_version"
annotationProcessor "android.arch.persistence.room:compiler:$room_version"
testImplementation "android.arch.persistence.room:testing:$room_version"
}