android-PageKeyedDataSource loadAfter不会被触发

android-PageKeyedDataSource loadAfter不会被触发,第1张

概述在我的片段中,我将AndroidJetpack分页库和数据源集成在一起,将PageKeyedDataSource与翻新API回调一起使用.代码以例外方式运行,并将数据加载到recyclerview中,但是在我滚动到底部之后,它应该通过在数据源类中触发loadAfter函数来加载更多数据,但是没有我也切换到ItemKeyedDataSo

在我的片段中,我将Android Jetpack分页库和数据源集成在一起,将PageKeyedDataSource与翻新API回调一起使用.

代码以例外方式运行,并将数据加载到recyclervIEw中,但是在我滚动到底部之后,它应该通过在数据源类中触发loadAfter函数来加载更多数据,但是没有

我也切换到ItemKeyedDataSource仍然无法执行

是我的代码错误或插件有问题!但是在一些我在GitHub上找到的演示应用程序中,我可以按照上面的代码完美地工作.如果有人遇到问题并解决,请告诉我
编辑:使用AndroIDX

public class ReportsDataSource extends PageKeyedDataSource<Integer, ReportItemmodel> {    mutablelivedata<NetworkState> networkState = new mutablelivedata<>();    mutablelivedata<NetworkState> initialLoad = new mutablelivedata<>();    private UserService getUserService;    private List<Call<?>> compositedisposable;    private Compositedisposable compositedisposableData;    private SchedulerProvIDer schedulerProvIDer;    private Completable retryCompletable = null;    public ReportsDataSource(UserService getUserService, List<Call<?>> compositedisposable, Compositedisposable compositedisposableData, SchedulerProvIDer schedulerProvIDer) {        this.getUserService = getUserService;        this.compositedisposable = compositedisposable;        this.compositedisposableData = compositedisposableData;        this.schedulerProvIDer = schedulerProvIDer;    }    @OverrIDe    public voID loadInitial(@NonNull LoadInitialParams<Integer> params, @NonNull LoadInitialCallback<Integer, ReportItemmodel> callback) {        networkState.postValue(NetworkState.LOADING);        initialLoad.postValue(NetworkState.LOADING);        loadPage(1, new callback() {            @OverrIDe            public voID get(ReportListModel List) {                setRetry(null);                networkState.postValue(NetworkState.LOADED);                initialLoad.postValue(NetworkState.LOADED);                callback.onResult(List.data.items, 1, List.data.next);            }            @OverrIDe            public voID failure(Throwable t) {                setRetry(() -> loadInitial(params, callback));                NetworkState error = NetworkState.error(t.getMessage());                networkState.postValue(error);                initialLoad.postValue(error);            }        });    }    @OverrIDe    public voID loadBefore(@NonNull LoadParams<Integer> params, @NonNull LoadCallback<Integer, ReportItemmodel> callback) {    }    @OverrIDe    public voID loadAfter(@NonNull LoadParams<Integer> params, @NonNull LoadCallback<Integer, ReportItemmodel> callback) {        networkState.postValue(NetworkState.LOADING);        loadPage(params.key, new callback() {            @OverrIDe            public voID get(ReportListModel List) {                setRetry(null);                networkState.postValue(NetworkState.LOADED);                callback.onResult(List.data.items, List.data.next != params.key ? null : List.data.next);            }            @OverrIDe            public voID failure(Throwable t) {                setRetry(() -> loadAfter(params, callback));                networkState.postValue(NetworkState.error(t.getMessage()));            }        });    }    public static voID log(String msg) {        boolean threadMain = Looper.getMainLooper().getThread() == Thread.currentThread();        Timber.tag("Thread_finder_" + (threadMain ? "ui" : "none")).d(Thread.currentThread().getID() + " " + msg);    }    private voID loadPage(int i, callback callback) {        log("loadPage");        Call<ReportListModel> call = getUserService.getReportsList(i);        compositedisposable.add(call);        try {            Response<ReportListModel> response = call.execute();            log("onResponse");            if (RetrofitHelper.isSuccessful(response)) {                callback.get(response.body());            } else {                callback.failure(new Throwable("Model verification is Failed"));            }        } catch (IOException e) {            callback.failure(e);            //e.printstacktrace();        }    }    public voID retry() {        if (retryCompletable != null) {            compositedisposableData.add(retryCompletable.subscribeOn(schedulerProvIDer.io()).observeOn(schedulerProvIDer.ui()).subscribe(() -> {            }, Timber::d));        }    }    private voID setRetry(Action action) {        if (action == null) {            this.retryCompletable = null;        } else {            this.retryCompletable = Completable.fromAction(action);        }    }    @NonNull    public mutablelivedata<NetworkState> getNetworkState() {        return networkState;    }    @NonNull    public mutablelivedata<NetworkState> getinitialLoad() {        return initialLoad;    }    public interface callback {        voID get(ReportListModel List);        voID failure(Throwable t);    }}

视图模型

public class ReportsListviewmodel extends viewmodel {    private static final int PAGE_SIZE = 10;    private Executor executor = Executors.newFixedThreadPool(5);    public liveData<PagedList<ReportItemmodel>> List;    private List<Call<?>> compositedisposable = new ArrayList<>();    private Compositedisposable compositedisposableData = new Compositedisposable();    private ReportsDataSourceFactory sourceFactory;    public final ObservableBoolean isErrorMessageVisible;    public final ObservableBoolean isRetrybuttonVisible;    public final ObservableBoolean isLoadingProgressbarVisible;    public final ObservableBoolean isSwipeRefreshLayoutEnable;    public final ObservableFIEld<String> errorMessage;    public ReportsListviewmodel(UserService userService, SchedulerProvIDer schedulerProvIDer) {        sourceFactory = new ReportsDataSourceFactory(userService, compositedisposable, compositedisposableData, schedulerProvIDer);        PagedList.Config config = new PagedList.Config.Builder()                .setPageSize(PAGE_SIZE)                .setEnablePlaceholders(false)                .build();        List = new livePagedListBuilder<>(sourceFactory, config).build();        isErrorMessageVisible = new ObservableBoolean(false);        errorMessage = new ObservableFIEld<>("");        isRetrybuttonVisible = new ObservableBoolean(false);        isLoadingProgressbarVisible = new ObservableBoolean(true);        isSwipeRefreshLayoutEnable = new ObservableBoolean(true);    }    @OverrIDe    protected voID onCleared() {        super.onCleared();        RetrofitStatic.clearRetrofitList(compositedisposable);        compositedisposableData.clear();    }    public voID retry() {        sourceFactory.getDataSourceliveData().getValue().retry();    }    public voID refresh() {        sourceFactory.getDataSourceliveData().getValue().invalIDate();    }    public liveData<NetworkState> getNetworkState() {        return transformations.switchMap(sourceFactory.getDataSourceliveData(), ReportsDataSource::getNetworkState);    }    public liveData<NetworkState> getRefreshState() {        return transformations.switchMap(sourceFactory.getDataSourceliveData(), ReportsDataSource::getinitialLoad);    }    public voID setinitialLoadingState(NetworkState networkState) {        isErrorMessageVisible.set((networkState.getMessage() != null));        errorMessage.set(networkState.getMessage());        isRetrybuttonVisible.set(networkState.getStatus() == NetworkStateStatus.Failed);        isLoadingProgressbarVisible.set(networkState.getStatus() == NetworkStateStatus.RUNNING);        isSwipeRefreshLayoutEnable.set(networkState.getStatus() == NetworkStateStatus.SUCCESS);    }}

Pagelistadapter

public class Reportlistadapter extends Pagedlistadapter<ReportItemmodel, RecyclerVIEw.VIEwHolder> {    public static final DiffUtil.ItemCallback<ReportItemmodel> DIFF_CALLBACK = new DiffUtil.ItemCallback<ReportItemmodel>() {        @OverrIDe        public boolean areItemsTheSame(@NonNull ReportItemmodel oldItem, @NonNull ReportItemmodel newItem) {            return oldItem.reportID == newItem.reportID;        }        @OverrIDe        public boolean areContentsTheSame(@NonNull ReportItemmodel oldItem, @NonNull ReportItemmodel newItem) {            return oldItem.equals(newItem);        }    };    private NetworkState networkState = null;    private RetryCallback retryCallback;    public Reportlistadapter(RetryCallback retryCallback) {        super(DIFF_CALLBACK);        this.retryCallback = retryCallback;    }    @OverrIDe    public int getItemVIEwType(int position) {        if (hasExtraRow() && position == getItemCount() - 1) {            return R.layout.item_network_state;        } else {            return R.layout.recycler_report_item;        }    }    @NonNull    @OverrIDe    public RecyclerVIEw.VIEwHolder onCreateVIEwHolder(@NonNull VIEwGroup parent, int vIEwType) {        VIEw vIEw;        switch (vIEwType) {            case R.layout.recycler_report_item:            default:                vIEw = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_report_item, parent, false);                return new VIEwHolder(vIEw);            case R.layout.item_network_state:                vIEw = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_network_state, parent, false);                return new NetWorkStateHolder(vIEw);        }    }    @OverrIDe    public voID onBindVIEwHolder(@NonNull RecyclerVIEw.VIEwHolder holder, int position) {        if (holder instanceof VIEwHolder) {            bindVIEw((VIEwHolder) holder, position, holder.itemVIEw.getContext());        } else if (holder instanceof NetWorkStateHolder) {            bindNetworkVIEw((NetWorkStateHolder) holder, position, holder.itemVIEw.getContext());        }    }    private voID bindNetworkVIEw(NetWorkStateHolder holder, int position, Context context) {        NetworkStateItemviewmodel mNetworkStateItemviewmodel = new NetworkStateItemviewmodel(networkState, retryCallback);        if (holder.binding != null) {            holder.binding.setviewmodel(mNetworkStateItemviewmodel);            holder.binding.executePendingBindings();        }    }    @OverrIDe    public int getItemCount() {        return super.getItemCount() + (hasExtraRow() ? 1 : 0);    }    private voID bindVIEw(VIEwHolder holder, int position, Context context) {        holder.binding.reportID.setText( "Report ID: "+position);    }    private boolean hasExtraRow() {        return networkState != null && networkState != NetworkState.LOADED;    }    public voID setNetworkState(NetworkState newNetworkState) {        if (getCurrentList() != null) {            if (getCurrentList().size() != 0) {                NetworkState prevIoUsstate = this.networkState;                boolean hadExtraRow = hasExtraRow();                this.networkState = newNetworkState;                boolean hasExtraRow = hasExtraRow();                if (hadExtraRow != hasExtraRow) {                    if (hadExtraRow) {                        notifyItemRemoved(super.getItemCount());                    } else {                        notifyItemInserted(super.getItemCount());                    }                } else if (hasExtraRow && prevIoUsstate != newNetworkState) {                    notifyItemChanged(getItemCount() - 1);                }            }        }    }    public class VIEwHolder extends RecyclerVIEw.VIEwHolder {        private final RecyclerReportItembinding binding;        public VIEwHolder(@NonNull VIEw itemVIEw) {            super(itemVIEw);            binding = DataBindingUtil.bind(itemVIEw);        }    }    public class NetWorkStateHolder extends RecyclerVIEw.VIEwHolder {        private final ItemNetworkStateBinding binding;        private final NetworkStateItemviewmodel mNetworkStateItemviewmodel;        public NetWorkStateHolder(@NonNull VIEw itemVIEw) {            super(itemVIEw);            mNetworkStateItemviewmodel = new NetworkStateItemviewmodel(networkState, retryCallback);            binding = DataBindingUtil.bind(itemVIEw);            binding.setviewmodel(mNetworkStateItemviewmodel);            binding.executePendingBindings();        }    }}

分段:

public class ReportsFragment extends ParentFragment implements RetryCallback {    private ReportsFragment.callback callback;    private FragmentReportsListBinding binding;    private ReportsListviewmodel reportviewmodel;    private Reportlistadapter adapter;    public voID setup(callback callback) {        this.callback = callback;    }    @Nullable    @OverrIDe    public VIEw onCreateVIEw(@NonNull LayoutInflater inflater, @Nullable VIEwGroup container, @Nullable Bundle savedInstanceState) {        super.onCreateVIEw(inflater, container, savedInstanceState);        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_reports_List, container, false);        reportviewmodel = viewmodelProvIDers.of(this, mviewmodelFactory).get(ReportsListviewmodel.class);        binding.setviewmodel(reportviewmodel);        binding.executePendingBindings();        initAdapter();        initSwipetoRefresh();        return binding.getRoot();    }    private voID initSwipetoRefresh() {        reportviewmodel.getRefreshState().observe(this, networkState -> {            if (adapter.getCurrentList() != null) {                if (adapter.getCurrentList().size() > 0) {                    binding.useRSSwipeRefreshLayout.setRefreshing(networkState != null && networkState.getStatus() == NetworkState.LOADING.getStatus());                } else {                    setinitialLoadingState(networkState);                }            } else {                setinitialLoadingState(networkState);            }        });    }    private voID setinitialLoadingState(NetworkState networkState) {        reportviewmodel.setinitialLoadingState(networkState);    }    private voID initAdapter() {        linearlayoutmanager linearlayoutmanager = new linearlayoutmanager(getContext());        adapter = new Reportlistadapter(this);        binding.recycler.setLayoutManager(linearlayoutmanager);        binding.recycler.setAdapter(adapter);        reportviewmodel.List.observe(this,  adapter::submitList);        reportviewmodel.getNetworkState().observe(this, adapter::setNetworkState);    }    @OverrIDe    public voID retry() {        reportviewmodel.retry();    }    public interface callback {    }}

XML

<?xml version="1.0" enCoding="utf-8"?><layout xmlns:androID="http://schemas.androID.com/apk/res/androID"    xmlns:app="http://schemas.androID.com/apk/res-auto">    <data>        <import type="androID.vIEw.VIEw" />        <variable            name="viewmodel"            type="daSarahalli.portal.adapters.paging.reports.ReportsListviewmodel" />    </data>    <androIDx.coordinatorlayout.Widget.CoordinatorLayout        androID:layout_wIDth="match_parent"        androID:layout_height="match_parent"        androID:orIEntation="vertical">        <androIDx.swiperefreshlayout.Widget.SwipeRefreshLayout            androID:ID="@+ID/useRSSwipeRefreshLayout"            androID:layout_wIDth="match_parent"            androID:layout_height="match_parent"            androID:enabled="@{viewmodel.isSwipeRefreshLayoutEnable}"            app:onRefreshListener="@{viewmodel::refresh}">            <androIDx.recyclervIEw.Widget.RecyclerVIEw                androID:ID="@+ID/recycler"                androID:layout_wIDth="match_parent"                androID:layout_height="match_parent" />        </androIDx.swiperefreshlayout.Widget.SwipeRefreshLayout>        <linearLayout            androID:layout_wIDth="match_parent"            androID:layout_height="wrap_content"            androID:layout_gravity="center"            androID:orIEntation="vertical"            androID:padding="8dp">            <TextVIEw                androID:ID="@+ID/errorMessageTextVIEw"                androID:layout_wIDth="wrap_content"                androID:layout_height="wrap_content"                androID:layout_gravity="center_horizontal"                androID:text="@{viewmodel.errorMessage}"                androID:visibility="@{viewmodel.isErrorMessageVisible ? VIEw.VISIBLE : VIEw.GONE}" />            <Progressbar                androID:ID="@+ID/loadingProgressbar"                                androID:layout_wIDth="match_parent"                androID:layout_height="wrap_content"                androID:layout_gravity="center"                androID:visibility="@{viewmodel.isLoadingProgressbarVisible ? VIEw.VISIBLE : VIEw.GONE}" />            <button                androID:ID="@+ID/retryLoadingbutton"                                androID:layout_wIDth="wrap_content"                androID:layout_height="wrap_content"                androID:layout_gravity="center"                androID:onClick="@{() -> viewmodel.retry()}"                androID:text="RETRY"                androID:visibility="@{viewmodel.isRetrybuttonVisible ? VIEw.VISIBLE : VIEw.GONE}" />        </linearLayout>    </androIDx.coordinatorlayout.Widget.CoordinatorLayout></layout>

解决方法:

在上面的代码中,您可以看到我没有在onBindVIEwHolder下调用getitem,但是在我请求getItem(itemPostion)之后,它全部开始工作了,它应该是

示范项目:

androidx-paging-library-demo-java

总结

以上是内存溢出为你收集整理的android-PageKeyedDataSource loadAfter不会被触发全部内容,希望文章能够帮你解决android-PageKeyedDataSource loadAfter不会被触发所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1094172.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-28
下一篇 2022-05-28

发表评论

登录后才能评论

评论列表(0条)

保存