我有一个简单的应用程序,而我正在尝试了解android / room。我希望将我的查询从房间放入我的列表视图。
PersonDao.class
@Query("Select name from People limit 3")
LiveData<List<String>> getThreeNames();
AvtivityMain.class
private ArrayAdapter<String> adapter;
private PersonDatabase db;
private EditText age;
private EditText name;
Person person;
private DatabaseRepository rDb;
private PersonViewModel personViewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = findViewById(R.id.name);
age = findViewById(R.id.age);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
ListView lvPerson = findViewById(R.id.lv3Poeple);
lvPerson.setAdapter(adapter);
personViewModel = ViewModelProviders.of(this).get(PersonViewModel.class);
}
public void addPerson(View view){
int sAge = Integer.parseInt(age.getText().toString());
String sName = name.getText().toString();
person = new Person(sName, sAge);
personViewModel.insert(person);
System.out.println(personViewModel.getmAllPeople());
System.out.println(personViewModel.getm3People());
//List<String> names = personViewModel.getm3People();
//adapter.add(personViewModel.getm3People());
}
我已经注释掉了我遇到问题的代码。我希望能够使用PersonDao的查询,并让我的列表视图显示我的房间数据库中的3个名字。
答案 0 :(得分:0)
您需要做一些事情,首先要确保您的适配器可以接受新的输入。我建议您创建自己的自定义商品。创建它时,请确保包括一个将您的人员字符串作为输入并通知适配器更改的方法,如下所示:
//you need to add an update method to your adapter, so it can change it's data as your
//viewmodel data changes, something like this:
public void setPersons(List<String> personNames) {
//myPersons should be a variable declared within your adapter that the views load info from
myPersons = personNames;
notifyDataSetChanged();
}
然后,在您的活动中,应将适配器设置为全局变量,以便可以通过多种方法(例如,视图模型观察器方法以及它在onCreate()
中的初始设置)进行访问。
//need to set up adapter variable to access in other methods to keep view model observer
//off the main thread
private ArrayAdapter myAdapter;
此后,您可以为ViewModel
设置以下观察者方法(假设您使用名为getThreeNames()
的返回方法正确创建了ViewModel类,并且该方法不仅仅显示在DAO中以上。
//set up the view model observer to be off the main thread so it isn't tied to your main
//activity lifecyle (which is the whole point/beauty of the ViewModel), you can call this
//method in your onCreate() method and should stay until onDestroy() is called
private void setupPersonViewModel() {
PersonViewModel viewModel
= ViewModelProviders.of(this).get(PersonViewModel.class);
viewModel.getThreeNames().observe(this, new Observer<List<String>>() {
@Override
public void onChanged(@Nullable List<String> persons) {
//so you can see when your app does this in your log
Log.d(TAG, "Updating list of persons from LiveData in ViewModel");
mAdapter.setPersons(persons);
}
});
}
希望能回答您的问题。让我知道是否需要进一步澄清。