如何在Android

时间:2016-09-05 19:46:38

标签: android android-recyclerview android-adapter android-json

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

要连接到互联网,我使用 Retrofit v2 ,对于Endless的自定义recyclerView方法我使用此类: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$1$1.onResponse(Category_page.java:124)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.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);
}

活动代码:

 @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 数据?请帮助我亲爱的朋友。我真的需要你的帮助&lt; 3

1 个答案:

答案 0 :(得分:0)

问题是response.body()是一个R_CatModelResponse对象,但您要将其投射到List<R_CatModel>

如果R_CatModelResponse有一个方法以R_CatModel列表回复(例如getCatModelList()),那么你只需要使用它:

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