总是从room表接收空列表

kqhtkvqz  于 2021-06-27  发布在  Java
关注(0)|答案(1)|浏览(399)

我有一张有价值的房间table。我想对其中的一些值求和,但是我得到了一个错误。它在里面 otherArraySum() 方法和它是 NullPointerException . 我想知道为什么 otherAmountList 是空的,我怎么能修正它。先谢谢你。
查询

@Query("SELECT value FROM statistics_table WHERE category = 7")
        LiveData<List<Float>> otherList();

存储库

public Repository(Application application){
        AppDatabase database = AppDatabase.getInstance(application);
        otherList = statisticsDao.otherList();
}
public LiveData<List<Float>> getOtherList(){ 
        return otherList;
}

视图模型

public class StatisticsViewModel extends AndroidViewModel {
 LiveData<List<Float>> otherList;
 public StatisticsViewModel(@NonNull Application application) {
        super(application);
        repository = new Repository(application);
        otherList = repository.getOtherList();

public LiveData<List<Float>> getAllOtherList(){ 
    return otherList;
   }
}

活动

List<Float> otherAmountList;
statisticsViewModel = new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory
                .getInstance(this.getApplication())).get(StatisticsViewModel.class);
otherAmountList = statisticsViewModel.getAllOtherList().getValue();
otherAmount = otherArraySum();
public float otherArraySum() {
        float sum = 0;
        for(int i = 0; i < otherAmountList.size(); i++) {
            sum = sum + otherAmountList.get(i); }
        return sum; }

logcat公司

Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
        at com.example.moneymanager.MainActivity2.otherArraySum(MainActivity2.java:155)
i86rm4rw

i86rm4rw1#

通过将活动代码更改为以下内容解决了我的问题:

float sum;
statisticsViewModel = new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory
                .getInstance(this.getApplication())).get(StatisticsViewModel.class);
statisticsViewModel.getAllOtherList().observe(this, new Observer<List<Float>>() {
            @Override
            public void onChanged(List<Float> floats) {
                for(int i = 0; i < floats.size(); i++) {
                    sum = sum + floats.get(i); }           
            }
        });

相关问题