Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
272 views
in Technique[技术] by (71.8m points)

java - Always receiving null list from room table

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Solved my problem by changing activity code to this:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...