带有ArrayAdapter的Android LiveData到列表视图

问题描述 投票:0回答:1

您好,我试图在主要活动中将实时数据添加到我的列表视图数据适配器中,但是遇到了麻烦,有人可以给我一个为什么这不起作用的想法吗?

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

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

android android-arrayadapter android-livedata
1个回答
0
投票

您只需要观察者这样的记录中的实时数据

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 String newName) {
                // Update the UI, in this case, a TextView.
                ArrayAdapter adapter = new ArrayAdapter(this,
                         android.R.layout.simple_list_item_1, android.R.id.text1, mAllRecords);
                lv.setAdapter(adapter);
            }
        };

viewModel.mAllRecords().observe(this, nameObserver);

如果我错了,请纠正我,因为如果在这里使用Kotlin, reference非常容易,>

© www.soinside.com 2019 - 2024. All rights reserved.