2

我已经使用如下简单的 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"
}
4

1 回答 1

0

永远不要使用这样的架构组件。您应该使用 MVVM,因为它们旨在解决此问题。模型应该包含您的数据,说明哪个房间可以做。然后,您的视图应该只包含演示文稿和对第三个组件 View-Model 的引用。您的代码中缺少 ViewModel,它是这样的:

public class WordViewModel extends ViewModel {
    private MutableLiveData<List<Word>> mWords;
    private AppDatabase mDb;

    public WordViewModel(@NonNull Application application) {
        super(application);

        mWords = new MutableLiveData<List<Word>>();
        mDb = AppDatabase.getInstance(application.getApplicationContext());
    }

    public LiveData<List<User>> getWords() {
        loadWords();

        return words;
    }

    private void loadWords() {
       return mDb.wordDao().getAll();
    }
}

然后您的活动将更改为

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final TextView tv = findViewById(R.id.textview);

    WordViewModel viewModel = ViewModelProviders.of(this).get(WordViewModel.class);
    viewModel.getWords().observe(this, new Observer<List<Word>>() {
        @Override
        public void onChanged(@Nullable ResponseDataList resp) {
            StringBuilder builder = new StringBuilder();

            for (Word w : wordlist ) {
                builder.append(w.word).append(", ");
            }

            tv.setText(builder.toString());
        }
    });
}

让我知道评论中是否有任何不清楚的地方

于 2018-06-25T16:18:20.593 回答