如何在 Android 中修复 RecyclerView 上的 addOnScrollListener 错误

How to fix bug for addOnScrollListener on RecyclerView in Android

我想从服务器加载数据并显示到我的应用程序中 (RecyclerView),对于此作业,当启动应用程序时我显示 10 个帖子,滚动时 recyclerView 显示另一个帖子。 我写了下面的代码但是当得到 10 个帖子时没有加载其他帖子并显示强制关闭错误!

对于连接到互联网,我使用 Retrofit v2,对于 recyclerView 的自定义 Endless 方法,我使用此 class:EndLess Class

LogCat 错误:

FATAL EXCEPTION: main
Process: com.tellfa.colony, PID: 25304
java.lang.ClassCastException: com.tellfa.colony.Retrofit.Model.Category.R_CatModelResponse cannot be cast to java.util.List
at com.tellfa.colony.Activities.Category_page.onResponse(Category_page.java:124)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall.run(ExecutorCallAdapterFactory.java:68)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5349)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)

Api接口代码:

public interface Retrofit_ApiInterface {

    // For load more category
    @GET("?json=get_category_posts")
    Call<R_CatModelResponse> getCatMoreResponse(@Query("id") Integer id, @Query("page") Integer page);
}

适配器代码:(我将此代码添加到我的适配器中,以加载更多数据)

public void addNewItem(List<R_CatModel> newContent) {
    int start = this.mDateSet.size();//contents is a List of your items initialize it your constructor
    int end = newContent.size();
    mDateSet.addAll(newContent);
    notifyItemRangeInserted(start + 1, end);
}

Activity 代码:

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.category_page);

        // Hide StatusBar color
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);

        // Initializing
        context = Category_page.this;
        toolbar = (Toolbar) findViewById(R.id.category_toolbar);
        cat_recyclerView = (RecyclerView) findViewById(R.id.category_recycler);
        toolbar_title = (TextView) toolbar.findViewById(R.id.toolbar_pages_title);
        mLayoutManager = new LinearLayoutManager(this);
        root = (RelativeLayout) findViewById(R.id.category_root);
        loadLayout = (RelativeLayout) findViewById(R.id.category_empty_layout);
        checkNetLayout = (RelativeLayout) findViewById(R.id.category_checkInternet_layout);
        categoryCheckNet_button = (Button) checkNetLayout.findViewById(R.id.checkNet_button);
        // Toolbar
        setSupportActionBar(toolbar);
        if (toolbar != null) {
            getSupportActionBar().setTitle("");
        }

        // Receive Data
        bundle = getIntent().getExtras();
        catID = bundle.getInt("categoryID");
        if (bundle != null) {
            catTitle = bundle.getString("categoryTitle");
        }
        if (catTitle != null) {
            toolbar_title.setText(catTitle);
        }

        // Load Data
        loadData();

        // Load Progress
        loadLayout.setVisibility(View.VISIBLE);

        // RecyclerView
        cat_recyclerView.setLayoutManager(mLayoutManager);
        cat_recyclerView.setHasFixedSize(true);
        cat_recyclerView.addOnScrollListener(new EndlessRecyclerOnScrollListener(mLayoutManager) {
            @Override
            public void onLoadMore(int current_page) {

                Retrofit_ApiInterface apiInterface = Retrofit_ApiClient.getClient().create(Retrofit_ApiInterface.class);
                Call<R_CatModelResponse> call = apiInterface.getCatMoreResponse(catID, current_page);

                call.enqueue(new Callback<R_CatModelResponse>() {
                    @Override
                    public void onResponse(Call<R_CatModelResponse> call, Response<R_CatModelResponse> response) {

                        if (response != null) {
                            mAdapter.addNewItem((List<R_CatModel>) response.body());
                            //loadLayout.setVisibility(View.GONE);
                        } else {
                            //loadLayout.setVisibility(View.VISIBLE);
                            Toast.makeText(Category_page.this, "Error 2", Toast.LENGTH_SHORT).show();
                            TastyToast.makeText(context, "خطايي رخ داده است", TastyToast.LENGTH_LONG, TastyToast.ERROR);
                        }
                    }

                    @Override
                    public void onFailure(Call<R_CatModelResponse> call, Throwable t) {

                    }
                });
            }
        });

    }

    private void loadData() {
        boolean isConnected = ConnectivityReceiver.isConnected();

        retrofitData(isConnected);
    }

    private void retrofitData(boolean isConnect) {

        if (isConnect) {
            Retrofit_ApiInterface apiInterface = Retrofit_ApiClient.getClient().create(Retrofit_ApiInterface.class);
            Call<R_CatModelResponse> call = apiInterface.getCatResponse(catID);

            call.enqueue(new Callback<R_CatModelResponse>() {
                @Override
                public void onResponse(Call<R_CatModelResponse> call, Response<R_CatModelResponse> response) {

                    if (response != null) {
                        models = response.body().getCat_posts();

                        mAdapter = new CategoryAdapter(context, cat_recyclerView, models);
                        cat_recyclerView.setAdapter(mAdapter);
                        loadLayout.setVisibility(View.GONE);

                    } else {
                        //loadLayout.setVisibility(View.VISIBLE);
                        Toast.makeText(Category_page.this, "Error 2", Toast.LENGTH_SHORT).show();
                        TastyToast.makeText(context, "خطايي رخ داده است", TastyToast.LENGTH_LONG, TastyToast.ERROR);
                    }

                    checkNetLayout.setVisibility(View.GONE);
                }

                @Override
                public void onFailure(Call<R_CatModelResponse> call, Throwable t) {

                    //loadLayout.setVisibility(View.VISIBLE);
                    //TastyToast.makeText(context, "لطفا برنامه را مجددا باز کنيد", TastyToast.LENGTH_LONG, TastyToast.ERROR);
                    Toast.makeText(Category_page.this, "Error 2", Toast.LENGTH_SHORT).show();
                    //Cat_EmptyLayout.setVisibility(View.VISIBLE);
                    Log.e("CatResponseError", "Error : " + t);

                }
            });
        } else {
            //loadLayout.setVisibility(View.GONE);
            checkNetLayout.setVisibility(View.VISIBLE);
            if (mAdapter != null) {
                mAdapter.clear();
                cat_recyclerView.setAdapter(mAdapter);
            }
            categoryCheckNet_button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    loadData();
                }
            });
        }
    }

}

我该如何解决这个问题并根据上述代码在 recyclerView 中设置 loadMore 数据?!请帮助我亲爱的朋友。我真的需要你的帮助 <3

问题是 response.body() 是一个 R_CatModelResponse 对象,但您将其转换为 List<R_CatModel>

如果 R_CatModelResponse 有一个响应列表 R_CatModel 的方法(例如 getCatModelList()),那么您只需要使用它:

mAdapter.addNewItem(response.body().getCatModelList());