Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...