首页 > 解决方案 > 通过 Dao、Repository 和 Viewmodel 从 Room 数据库接收对象列表的问题。找不到错误

问题描述

我在 Dao、Repository、ViewModel 和 Activity 中有方法来获取人员列表,但最后我得到空列表(空对象引用错误)。哪里可能出错?非常感谢..

个人道:

@Dao
public interface PersonDao {
    //other methods of PersonDao

    @Query("SELECT * FROM person_table WHERE status = :status ORDER BY RANDOM() LIMIT 5")
    List<Person> getFivePersonsFrom(String status);
} 

在 PersonRepository 中:

public class PersonRepository {
    private PersonDao mPersonDao;
    private List<Person> mFivePersonsFrom;

    //other methods

    List<Person> getFivePersonsFrom(String status) {
        PersonRoomDatabase.databaseWriteExecutor.execute(() -> {
            mPersonDao.getFivePersonsFrom("noob");
        });
        return mFivePersonsFrom;
    }
}

在 PersonViewModel 中:

public class PersonViewModel extends AndroidViewModel {
    private PersonRepository mRepository;
    public List<Person> mFivePersonsFrom;
    public PersonViewModel(@NonNull Application application) {
        super(application);
        mRepository = new PersonRepository(application);
        mFivePersonsFrom = mRepository.getFivePersonsFrom("noob");
        //other methods
    }
    public List<Person> getFivePersonsFrom() {
        mRepository.getFivePersonsFrom("noob");
        return mFivePersonsFrom;
    }  
}

在 MainActivity 中:

private CardStackView noobCardStackView;
private NoobAdapter noobAdapter;
List<Person> noobList;     
// other
protected void onCreate(Bundle savedInstanceState) {
    noobViewModel = new ViewModelProvider(this,
            ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication()))
            .get(PersonViewModel.class);
    noobList = noobiewModel.getFivePersonsFrom();
noobAdapter = new NoobAdapter(new NoobAdapter.NoobDiff(), noobList); 
    noobCardStackView.setAdapter(noobAdapter);
    // methods
}

标签: javaandroidmvvmandroid-roomandroid-viewmodel

解决方案


推荐阅读