I have have room table with some values. I want to sum some of that values, but I am getting error. It is in otherArraySum()
method and it is NullPointerException
. I am wondering why otherAmountList
is null and how I can fix that. Thank you in advance.
Query
@Query("SELECT value FROM statistics_table WHERE category = 7")
LiveData<List<Float>> otherList();
Repository
public Repository(Application application){
AppDatabase database = AppDatabase.getInstance(application);
otherList = statisticsDao.otherList();
}
public LiveData<List<Float>> getOtherList(){
return otherList;
}
ViewModel
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;
}
}
Activity
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)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…