开发者社区> 问答> 正文

带有ArrayAdapter的Android LiveData到列表视图

嗨,我试图在主活动中将实时数据添加到我的列表视图数据适配器中,但是遇到了麻烦,有人可以告诉我为什么它不起作用吗?

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);

我不清楚将实时数据转换为阵列适配器

展开
收起
Puppet 2019-12-05 13:18:25 474 0
1 条回答
写回答
取消 提交回答
  • 您只需要观察者这样的记录中的实时数据

    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,这很容易,请参考这里

    2019-12-05 13:18:59
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
58同城Android客户端Walle框架演进与实践之路 立即下载
Android组件化实现 立即下载
蚂蚁聚宝Android秒级编译——Freeline 立即下载