嗨,我试图在主活动中将实时数据添加到我的列表视图数据适配器中,但是遇到了麻烦,有人可以告诉我为什么它不起作用吗?
RecordViewModel:
public class RecordViewModel extends AndroidViewModel {
private Repository mRepository;
public static LiveData<List<Record>> mAllRecords;
public RecordViewModel (Application application) {
super(application);
mRepository = new Repository(application);
mAllRecords = mRepository.getAllRecords();
}
public LiveData<List<Record>> getAllWords() {
mAllRecords=mRepository.getAllRecords();
return mAllRecords; }
主要活动:
import static ca.georgebrown.comp3074.TeranKevin.RecordViewModel.mAllRecords;
public class MainActivity extends AppCompatActivity implements SensorEventListener {
viewModel = new RecordViewModel(getApplication());
//should I use viewModel.getAllWords() to fetch data from database into mAllRecords?
@Override
protected void onCreate(Bundle savedInstanceState) {
lv = findViewById(R.id.listview);
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, android.R.id.text1, mAllRecords);
//I am getting error here, can't resolve constructor
lv.setAdapter(adapter);
我不清楚将实时数据转换为阵列适配器
您只需要观察者这样的记录中的实时数据
import static ca.georgebrown.comp3074.TeranKevin.RecordViewModel.mAllRecords;
public class MainActivity extends AppCompatActivity implements SensorEventListener {
viewModel = new RecordViewModel(getApplication());
//should I use viewModel.getAllWords() to fetch data from database into mAllRecords? yes you should do it on OnCreate
@Override
protected void onCreate(Bundle savedInstanceState) {
lv = findViewById(R.id.listview);
viewModel.getAllWords();
final Observer<List<Record>> wordObserve = new Observer<List<Record>>() {
@Override
public void onChanged(@Nullable final allRecords List<Record>) {
// Update the UI, in this case, a TextView.
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, android.R.id.text1, allRecords);
lv.setAdapter(adapter);
}
};
viewModel.mAllRecords().observe(this, wordObserve);
如果我错了,请纠正我,因为如果使用Kotlin,这很容易,请参考这里
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。