没有附加适配器,以跳过recyclerview的布局

时间:2019-07-31 07:23:30

标签: android android-recyclerview

嗨,在下面的代码中,使用recyclerview显示列表时出现以下错误。 当我尝试显示列表时,出现以下错误。

java.lang.ClassCastException: java.lang.String cannot be cast to helper.GetBuildingList
        at com.deepshikha.lightingsystem.SwipeRecyclerViewAdapter.onBindViewHolder(SwipeRecyclerViewAdapter.java:41)
        at com.deepshikha.lightingsystem.SwipeRecyclerViewAdapter.onBindViewHolder(SwipeRecyclerViewAdapter.java:22)
        at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6781)
        at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6823)

响应:

[{"ID":"1","Name":"Building1"},{"ID":"2","Name":"appexx"}]

在下面的适配器中显示getbuildinglist pojo类中显示的内容。以及用户从右向左滑动后,我们将显示两个选项供列表项目编辑和删除。

SwipeAdapter:

public class SwipeRecyclerViewAdapter extends RecyclerSwipeAdapter<SwipeRecyclerViewAdapter.SimpleViewHolder> {


    private Context mContext;
    private List<GetBuildingList> buildingLists;

    public SwipeRecyclerViewAdapter(Context context, List<GetBuildingList> strings) {
        this.mContext = context;
        this.buildingLists = strings;
    }

    @Override
    public SimpleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item, parent, false);
        return new SimpleViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final SimpleViewHolder viewHolder, final int position) {
        final GetBuildingList item = buildingLists.get(position);
        System.out.println ("item"+item);

        viewHolder.tvName.setText((item.getName ()) + "  -  Row Position " + position);
        System.out.println (item.getName ());


        viewHolder.swipeLayout.setShowMode(SwipeLayout.ShowMode.PullOut);

        // Drag From Left
//        viewHolder.swipeLayout.addDrag(SwipeLayout.DragEdge.Left, viewHolder.swipeLayout.findViewById(R.id.bottom_wrapper1));

        // Drag From Right
        viewHolder.swipeLayout.addDrag(SwipeLayout.DragEdge.Right, viewHolder.swipeLayout.findViewById(R.id.bottom_wrapper));


        // Handling different events when swiping
        viewHolder.swipeLayout.addSwipeListener(new SwipeLayout.SwipeListener() {
            @Override
            public void onClose(SwipeLayout layout) {
                //when the SurfaceView totally cover the BottomView.
            }

            @Override
            public void onUpdate(SwipeLayout layout, int leftOffset, int topOffset) {
                //you are swiping.
            }

            @Override
            public void onStartOpen(SwipeLayout layout) {

            }

            @Override
            public void onOpen(SwipeLayout layout) {
                //when the BottomView totally show.
            }

            @Override
            public void onStartClose(SwipeLayout layout) {

            }

            @Override
            public void onHandRelease(SwipeLayout layout, float xvel, float yvel) {
                //when user's hand released.
            }
        });

        /*viewHolder.swipeLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                if ((((SwipeLayout) v).getOpenStatus() == SwipeLayout.Status.Close)) {
                    //Start your activity

                    Toast.makeText(mContext, " onClick : " + item.getName() + " \n" + item.getEmailId(), Toast.LENGTH_SHORT).show();
                }

            }
        });*/

        viewHolder.swipeLayout.getSurfaceView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(mContext, " onClick : " + item.getName () + " \n" + item.getID (), Toast.LENGTH_SHORT).show();
            }
        });


//        viewHolder.btnLocation.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//                Toast.makeText(v.getContext(), "Clicked on Map " + viewHolder.tvName.getText().toString(), Toast.LENGTH_SHORT).show();
//            }
//        });
//
//
//        viewHolder.tvShare.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//
//                Toast.makeText(view.getContext(), "Clicked on Share " + viewHolder.tvName.getText().toString(), Toast.LENGTH_SHORT).show();
//            }
//        });

        viewHolder.tvEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Toast.makeText(view.getContext(), "Clicked on Edit  " + viewHolder.tvName.getText().toString(), Toast.LENGTH_SHORT).show();
            }
        });


        viewHolder.tvDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mItemManger.removeShownLayouts(viewHolder.swipeLayout);
                buildingLists.remove(position);
                notifyItemRemoved(position);
                notifyItemRangeChanged(position, buildingLists.size());
                mItemManger.closeAllItems();
                Toast.makeText(view.getContext(), "Deleted " + viewHolder.tvName.getText().toString(), Toast.LENGTH_SHORT).show();
            }
        });


        // mItemManger is member in RecyclerSwipeAdapter Class
        mItemManger.bindView(viewHolder.itemView, position);

    }

    @Override
    public int getItemCount() {
        return buildingLists.size();
    }

    @Override
    public int getSwipeLayoutResourceId(int position) {
        return R.id.swipe;
    }


    //  ViewHolder Class

    public static class SimpleViewHolder extends RecyclerView.ViewHolder {
        SwipeLayout swipeLayout;
        TextView tvName;
        TextView tvDelete;
        TextView tvEdit;


        public SimpleViewHolder(View itemView) {
            super(itemView);
            swipeLayout = (SwipeLayout) itemView.findViewById(R.id.swipe);
            tvName = (TextView) itemView.findViewById(R.id.tvName);
         //   tvEmailId = (TextView) itemView.findViewById(R.id.tvEmailId);
            tvDelete = (TextView) itemView.findViewById(R.id.tvDelete);
            tvEdit = (TextView) itemView.findViewById(R.id.tvEdit);
          //  tvShare = (TextView) itemView.findViewById(R.id.tvShare);
         //   btnLocation = (ImageButton) itemView.findViewById(R.id.btnLocation);


        }
    }
}

在下面的代码中描述了不刷新活动的情况,我正在从服务器获取响应。 我添加到arraylist的响应,然后将适配器设置为recyclerview以显示带有滑动选项的项目列表。

Add.java:

private void doTheAutoRefresh() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                // Write code for your refresh logic

                progressDialog = new ProgressDialog (getActivity ());
                progressDialog.setIndeterminate(true);
                progressDialog.setMessage("Communicating...");
                progressDialog.setCanceledOnTouchOutside(false);
                progressDialog.setCancelable(false);
                progressDialog.show();
                OkHttpClient client = new OkHttpClient.Builder()
                        .connectTimeout(10, TimeUnit.SECONDS)
                        .writeTimeout(10, TimeUnit.SECONDS)
                        .readTimeout(30, TimeUnit.SECONDS)
                        .build();

                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl(API.URL_BASE)
                        .addConverterFactory(ScalarsConverterFactory.create())
                        .addConverterFactory(GsonConverterFactory.create())
                        .client (client)
                        .build();
                API service = retrofit.create (API.class);
                Call<List<GetBuildingList>> userCall = service.getbuildinglist ();
                userCall.enqueue(new Callback<List<GetBuildingList>> () {

                    @Override
                    public void onResponse(Call <List<GetBuildingList>> call, Response <List<GetBuildingList>> response) {


                        if(response.isSuccessful()) {
                            progressDialog.dismiss ( );
                            Log.d ("Response body", new Gson ( ).toJson (response.body ( )));
                            String Status = new Gson ( ).toJson (response.body ( ));
                            JSONArray jsonArray = null;

                            try {
                                JSONObject jsonObject=null;
                                jsonArray = new JSONArray (Status);
                                arrayList = new ArrayList <> ( );

                                for (int i=0;i<jsonArray.length ();i++) {
                                    name=jsonArray.getJSONObject (i).getString ("Name");


                                    arrayList.add (name);

                                }

                                // Creating Adapter object
                                SwipeRecyclerViewAdapter mAdapter = new SwipeRecyclerViewAdapter((Context) getActivity (), arrayList);
                                mAdapter.notifyDataSetChanged ();
                                mRecyclerView.setAdapter(mAdapter);



                            } catch (JSONException e) {
                                e.printStackTrace ( );

                            }

                        }

                        else  {
                            progressDialog.dismiss ();
                            Log.d("Response errorBody", String.valueOf(response.errorBody()));
                        }

                    }

                    @Override
                    public void onFailure(Call<List<GetBuildingList>> call, Throwable t) {
                        // lv.setAdapter (adapter);
                        System.out.println("onFailure");
                        System.out.println(t.fillInStackTrace());
                        progressDialog.dismiss();
                        Toast.makeText(getActivity (), "Some error occurred -> ", Toast.LENGTH_LONG).show();;
                        // progressDialog.dismiss();



                    }

                });
            }


        }, 5000);
        return ;
    }

GetBuildingList.java:

public class GetBuildingList{

    @SerializedName("ID")
    private String ID;

    @SerializedName("Name")
    private String Name;

    public String getID() {
        return ID;
    }

    public void setID(String ID) {
        this.ID = ID;
    }

    public String getName() {
        return Name;
    }

    public void setName(String name) {
        Name = name;
    }


}

1 个答案:

答案 0 :(得分:1)

在您的onResponse()方法中,这些行如下:

name=jsonArray.getJSONObject (i).getString ("Name");
...
arrayList.add (name);

然后将此列表传递给适配器。该列表已分配给适配器的GetBuildingList字段。然后在适配器中执行以下操作:

final GetBuildingList item = buildingLists.get(position);

因此,您尝试将String类型转换为GetBuildingList类型,因此是例外。

对图书馆不是很熟悉,但是您应该尝试这样的事情:

for (int i=0;i<jsonArray.length ();i++) {
    String name = jsonArray.getJSONObject (i).getString ("Name");
    String id = jsonArray.getJSONObject (i).getString ("Id");
    GetBuildingList gbl = new GetBuildingList();
    gbl.setId(id);
    gbl.setName(name);
    arrayList.add(gbl);
}

我还没有使用过这个库,所以如果我错了,请有人更正上面的示例。