LivePagedListBuilder无法识别数据库中的新数据

时间:2019-05-26 10:17:00

标签: android-recyclerview android-room android-paging android-paging-library

我已按照本教程设置了Google Paging Library:https://guides.codepath.com/android/Paging-Library-Guide

使用Room从sqlite表中获取数据。

将新数据添加到sqlite表时,不会调用观察者。所以我的recyclerview不显示它。这是LivePagedListBuilder中的错误吗?

   PagedList.Config config = new PagedList.Config.Builder().setEnablePlaceholders(true).setPageSize(4).build();
    MessageDataSourceFactory factory = new MessageDataSourceFactory(this);
    this.messageListLiveData = new LivePagedListBuilder(factory, config).build();

    this.messageListLiveData.observe(this, new Observer<PagedList<MessageEntity>>() {
        @Override
        public void onChanged(@Nullable PagedList<MessageEntity> messageEntities) {
            adapter.submitList(messageEntities);
        }
    });

DataSourceFactory

public class MessageDataSourceFactory extends DataSource.Factory<Long, MessageEntity> {
    Context context;

    public MessageDataSourceFactory(Context context) {
        this.context = context;
    }

    @Override
    public DataSource<Long, MessageEntity> create() {
        MessageDataSource dataSource = new MessageDataSource(context);
        return dataSource;
    }
}

数据源

public class MessageDataSource extends ItemKeyedDataSource<Long, MessageData> {
    Context context;

    public MessageDataSource(Context context) {
        this.context = context;
    }

    @NonNull
    @Override
    public Long getKey(@NonNull MessageData item) {
        return item.getIndex();
    }

    public void loadInitial(@NonNull LoadInitialParams<Long> params, @NonNull final LoadInitialCallback<MessageData> callback) {
        // DAO loads initial data
        callback.onResult(messages);
    }

    // Called repeatedly when more data needs to be set
    @Override
    public void loadAfter(@NonNull LoadParams<Long> params, @NonNull LoadCallback<MessageData> callback) {
        if(params.key == 0) {
            return;
        }

        // DAO loads more data
        callback.onResult(messages);
    }

    @Override
    public void loadBefore(@NonNull LoadParams<Long> params, @NonNull LoadCallback<MessageData> callback) {
    }
}

另一种方法是创建一个返回的查询

DataSource.Factory<Integer, MessageEntity>

但是我想拥有自己的DataSource类。

0 个答案:

没有答案