如何在同一recyclerview的适配器类中更新recyclerview?

时间:2018-12-21 23:54:32

标签: android android-recyclerview recycler-adapter

我有一个recyclerview。我想从其适配器类更新回收器视图。 我尝试了notiftDataSetChanged( ),但是它只能在主类中使用。 下面是recyclerview适配器类的代码。

package com.library.apple.food;

import android.content.Context;
import android.content.Intent;


public class CartAdapter extends 
RecyclerView.Adapter<CartAdapter.MyViewHolder> {

private Context context;
private List<CartItem> list;
private String auth_token;
private RecyclerView recyclerView;

public CartAdapter(Context context, List<CartItem> list, String 
auth_token, RecyclerView recyclerView){
    this.context = context;
    this.list = list;
    this.auth_token = auth_token;
    this.recyclerView = recyclerView;


}



@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, 
int i) {
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.row_cart,viewGroup,false);
    CartAdapter.MyViewHolder myViewHolder = new 
    CartAdapter.MyViewHolder(view);
    return myViewHolder;
}

@Override
public void onBindViewHolder(@NonNull MyViewHolder viewHolder, 
final int i) {

    final CartItem item = list.get(i);

    viewHolder.title_cart.setText(item.getTitle_cart());
    viewHolder.no_cart.setText(item.getNo_cart());

    String price1 = context.getString(R.string.price,item.getPrice_cart());

    viewHolder.price_cart.setText(price1);


    String veg = item.getVegnon_cart();
    if (veg.equalsIgnoreCase("false")) {
        viewHolder.vegnon_cart.setImageResource(R.drawable.non_veg);

    }


    //-----------------------------------------------------------------------------


    //cart plus button
    viewHolder.btn_plus_cart.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(final View view) {

            String url_plus = "https://www.hungermela.com/api/v1/change-quantity/";
            final String item_id = item.getCart_item_id();


            RequestQueue queue = Volley.newRequestQueue(context);

            StringRequest postRequest = new StringRequest(Request.Method.POST, url_plus,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            // response
                            Log.d("Response", response);

//HERE I WANT TO UPDATE MY RECYCLERVIEW




                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            // error
                            Log.d("Error.Response", error.toString());

                        }
                    }
            ) {


                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    Map<String, String> params = new HashMap<String, String>();

                    params.put("Authorization", "Token "+auth_token);
                    return params;
                }


                @Override
                protected Map<String, String> getParams() {
                    Map<String, String> params = new HashMap<String, String>();
                    params.put("pk", item_id);

                    int quantity = Integer.parseInt(item.getNo_cart());
                    String quan = String.valueOf(quantity+1);
                    params.put("quantity",quan);

                    return params;
                }
            };
            queue.add(postRequest);




        }
    });
    //cart plus ends here


    //-----------------------------------------------------------------------------


    //cart minus button
    viewHolder.btn_minus_cart.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(final View view) {

            int quantity = Integer.parseInt(item.getNo_cart());



            if(quantity==1){



                String url_minus = "https://www.hungermela.com/api/v1/delete-item/";
                final String item_id = item.getCart_item_id();



                RequestQueue queue = Volley.newRequestQueue(context);

                StringRequest postRequest = new StringRequest(Request.Method.POST, url_minus,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                // response
                                Log.d("Response", response);



                            AppCompatActivity activity = (AppCompatActivity) view.getContext();
                            Fragment myFragment = new CartFragment();

                            activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, myFragment).addToBackStack(null).commit();




                                notifyDataSetChanged();

                            }
                        },
                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                // error
                                Log.d("Error.Response", error.toString());

                            }
                        }
                ) {


                    @Override
                    public Map<String, String> getHeaders() throws AuthFailureError {
                        Map<String, String> params = new HashMap<String, String>();

                        params.put("Authorization", "Token "+auth_token);
                        return params;
                    }


                    @Override
                    protected Map<String, String> getParams() {
                        Map<String, String> params = new HashMap<String, String>();
                        params.put("pk", item.getId_id());



                        return params;
                    }
                };
                queue.add(postRequest);





            }



            else if(quantity > 1){


                String url_minus = "https://www.hungermela.com/api/v1/change-quantity/";
                final String item_id = item.getCart_item_id();



                RequestQueue queue = Volley.newRequestQueue(context);

                StringRequest postRequest = new StringRequest(Request.Method.POST, url_minus,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                // response
                                Log.d("Response", response);

                            AppCompatActivity activity = (AppCompatActivity) view.getContext();
                            Fragment myFragment = new CartFragment();

                            activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, myFragment).addToBackStack(null).commit();




                                notifyDataSetChanged();

                            }
                        },
                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                // error
                                Log.d("Error.Response", error.toString());

                            }
                        }
                ) {


                    @Override
                    public Map<String, String> getHeaders() throws AuthFailureError {
                        Map<String, String> params = new HashMap<String, String>();

                        params.put("Authorization", "Token "+auth_token);
                        return params;
                    }


                    @Override
                    protected Map<String, String> getParams() {
                        Map<String, String> params = new HashMap<String, String>();
                        params.put("pk", item_id);

                        int quantity = Integer.parseInt(item.getNo_cart());
                        String quan = String.valueOf(quantity-1);
                        params.put("quantity",quan);


                        return params;
                    }
                };
                queue.add(postRequest);



            }





        }
    });
    //cart minus ends here


    //-----------------------------------------------------------------------------




}

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

class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    TextView title_cart, no_cart, price_cart;
    ImageView vegnon_cart;
    Button btn_minus_cart, btn_plus_cart;

    public MyViewHolder(@NonNull View itemView) {
        super(itemView);

        vegnon_cart = (ImageView)itemView.findViewById(R.id.vegnon_cart);
        title_cart = (TextView)itemView.findViewById(R.id.title_cart);
        no_cart = (TextView)itemView.findViewById(R.id.no_cart);
        price_cart = (TextView)itemView.findViewById(R.id.price_cart);

        //Button
        btn_minus_cart = (Button) itemView.findViewById(R.id.btn_minus_cart);
        btn_plus_cart = (Button) itemView.findViewById(R.id.btn_plus_cart);
    }

    @Override
    public void onClick(View view) {

    }
}
}

我尝试使用notiftDataSetChanged(),但是没有用。它没有在运行时更新recyclerview。我必须再次刷新页面。 我想在单击我的recyclerview行中的加号按钮后立即更新recyclerview。

2 个答案:

答案 0 :(得分:1)

您可以做类似的事情

public void updateData( List<CartItem> newData)

 {
     list.clear();
     list.addAll(newData);
     this.notiftDataSetChanged( );

 }

或使用set功能仅更新一项

 public void updateOnlyOneItem(CartItem newItem,int position){
     this.list.set(position, newItem);
     this.notifyItemChanged();
 }

答案 1 :(得分:0)

问题可能是您单击加号或减号按钮时没有更新基数列表。例如,

final CartItem item = list.get(i);
viewHolder.btn_plus_cart.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(final View view) {
        int count = item.getNo_cart()+1; //may be you can use response from network
        item.setNo_cart(count); //update item
        notifyDataSetChanged();
    }
}

在调用notifyDataSetChanged()之前,您需要使用新数据更新carditem对象