尝试在空对象引用上调用虚拟方法'void androidx.lifecycle.LiveData.observeForever(androidx.lifecycle.Observer)'

时间:2019-07-08 07:24:10

标签: android

我在onZeroItemLoaded方法上遇到错误。我的MediatorLiveData已经在全局变量的顶部启动了,但是仍然抛出错误?有指导吗?我添加了logcat来跟踪我的代码在哪里抛出错误,但找不到解决方法

同样,我已经为mediatorLiveData创建了一个对象

存储库

public class Repository {
public static final String TAG = Objects.requireNonNull(Repository.class.getCanonicalName()).toUpperCase();
private static Repository repository;
private Database database;
private MediatorLiveData<PagedList<Rating>> mediatorLiveData = new MediatorLiveData<>();
private NetworkRating_DataSourceFactory networkRating_DataSourceFactory;
private Rating_NetworkRequest rating_networkRequest;



private Repository(Context context) {
    database = Database.getInstance(context);
    database.configureResultFromDatabase();
}

public static Repository getRepositoryInstance(Context context){
    if(repository == null){
        Log.i(TAG, "Intantiating repository");
        repository = new Repository(context);
    }
    return repository;
}

PagedList.BoundaryCallback<Rating> boundaryCallback = new PagedList.BoundaryCallback<Rating>() {
    @Override
    public void onZeroItemsLoaded() {
        super.onZeroItemsLoaded();
        Log.i(TAG, "PagedList.BoundaryCallback onZeroItemLoaded called");

        mediatorLiveData.addSource(database.getAllRatingRecord(), new Observer<PagedList<Rating>>() {
            @Override
            public void onChanged(PagedList<Rating> ratings) {
                Log.i(TAG, "mediatorLiveData changed");
                mediatorLiveData.setValue(ratings);
                mediatorLiveData.removeSource(database.getAllRatingRecord());
            }
        });
    }
};

public LiveData<PagedList<Rating>> getAllRatingRecord(){
    Log.i(TAG, "Requesting for get All Rating Record");
    networkRating_DataSourceFactory = new NetworkRating_DataSourceFactory();
    rating_networkRequest = new Rating_NetworkRequest(networkRating_DataSourceFactory, boundaryCallback);

    mediatorLiveData.addSource(rating_networkRequest.getAllRatingRecord(), new Observer<PagedList<Rating>>() {
        @Override
        public void onChanged(PagedList<Rating> ratings) {
            Log.i(TAG, "New data received.");
            mediatorLiveData.postValue(ratings);
        }
    });

    networkRating_DataSourceFactory
            .getAllRatingRecord()
            .observeOn(Schedulers.io())
            .subscribe(database.getDAO()::insertRating);

    return mediatorLiveData;

    }
}

0 个答案:

没有答案