0

I am beginner in android development. I am creating an Application in which there is recycleView with CardView. inside cardview I am using one TextView and One Switch button. when i change the button value to server it is updated there.

I want to know how to update my ViewHolder Class for every volley Response. because if ViewHolder is not updated nextTime, value will not change in server but Switch Button change the side.

MainClass.java

public class Light extends Fragment {

public static final String light_url = "http://192.168.0.7:8080/bizzonthego/Android/device_status.php";
private List<ItemList> LightList;
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;

View v;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    v = inflater.inflate(R.layout.light, container, false);

    recyclerView = (RecyclerView) v.findViewById(R.id.recyclerView);
    recyclerView.setHasFixedSize(true);
    layoutManager = new LinearLayoutManager(getActivity());
    recyclerView.setLayoutManager(layoutManager);


    LightList = new ArrayList<>();
    new Handler().postAtTime(new Runnable() {
        @Override
        public void run() {

            getData();

        }
    }, 1000);



    return v;
}

@Override
public void onStart() {
    super.onStart();

}

@Override
public void onResume() {
    super.onResume();
//        new Handler().postDelayed(new Runnable() {
//            @Override
//            public void run() {
//
//                getData();
//
//            }
//        }, 1000);
}

private void getData()
{

 final ProgressDialog loading = ProgressDialog.show(getActivity(), "Loading Data", "Please wait...", false, false);
    JsonArrayRequest jsonArrayRequest =new JsonArrayRequest(light_url, new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray response) {


           loading.dismiss();
            parseData(response);


        }
    },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    loading.dismiss();
                    Toast.makeText(getActivity(),"error to connect",Toast.LENGTH_SHORT).show();

                }
            });

    RequestQueue requestQueue = Volley.newRequestQueue(getActivity());

    //Adding request to the queue
    requestQueue.add(jsonArrayRequest);

}
private void parseData(JSONArray array){


    for(int i = 0; i<array.length(); i++) {
        ItemList lightValue = new ItemList();
        JSONObject json = null;
        try {
            json = array.getJSONObject(i);
            String battery = json.getString("device");
            String status = json.getString("status");


            lightValue.setItem(battery);
            lightValue.setStatus(status);

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

        LightList.add(lightValue);
    }



    //Finally initializing our adapter
    adapter = new CardView(LightList,getActivity());
    adapter.notifyDataSetChanged();

    //Adding adapter to recyclerview
    recyclerView.setAdapter(adapter);

    }
}

ViewHolder.java

public class CardView extends RecyclerView.Adapter<CardView.ViewHolder>{

List<ItemList> items;
private Context context;
public static final String POST_SWITCH_URL = "http://192.168.0.7:8080/bizzonthego/Android/device_control.php";



public CardView(List<ItemList> item, Context context){
    super();
//        items = new ArrayList<ItemList>();
//                   ItemList item = new ItemList();
//            item.setItem(names);
//
//            items.add(item);
    this.items = item;
    this.context =context;

}


@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.permisies_cardview, parent, false);
    ViewHolder viewHolder = new ViewHolder(v);
    return viewHolder;
}

@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
    final ItemList list =  items.get(position);

    holder.textViewName.setText(list.getItem());
    final String device = list.getItem();

    if(list.getStatus().equals("0"))
    {
        holder.mySwitch.setChecked(false);
        holder.mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                StringRequest stringRequest = new StringRequest(Request.Method.POST,POST_SWITCH_URL ,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String s) {

                                Toast.makeText(context, s, Toast.LENGTH_LONG).show();


                            }
                        },
                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError volleyError) {


                                //Showing toast
                                Toast.makeText(context, "error to connect", Toast.LENGTH_LONG).show();
                            }
                        }) {
                    @Override
                    protected java.util.Map<String, String> getParams() throws AuthFailureError {

                        Map<String, String> params = new Hashtable<String, String>();
                        final String control = "1";

                        params.put("device",device);
                        params.put("control",control);




                        return params;
                    }
                };

                //Creating a Request Queue
                RequestQueue requestQueue = Volley.newRequestQueue(context);

                //Adding request to the queue

                requestQueue.add(stringRequest);

            }
        });


    } else if(list.getStatus().equals("1"))
    {
        holder.mySwitch.setChecked(true);
        holder.mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                StringRequest stringRequest = new StringRequest(Request.Method.POST,POST_SWITCH_URL ,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String s) {

                                Toast.makeText(context, s, Toast.LENGTH_LONG).show();


                            }
                        },
                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError volleyError) {


                                //Showing toast
                                Toast.makeText(context, "error to connect", Toast.LENGTH_LONG).show();
                            }
                        }) {
                    @Override
                    protected java.util.Map<String, String> getParams() throws AuthFailureError {

                        Map<String, String> params = new Hashtable<String, String>();
                        final String control = "0";

                        params.put("device",device);
                        params.put("control",control);




                        return params;
                    }
                };

                //Creating a Request Queue
                RequestQueue requestQueue = Volley.newRequestQueue(context);

                //Adding request to the queue
                requestQueue.add(stringRequest);

            }
        });


    }




}

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

class ViewHolder extends RecyclerView.ViewHolder{

    public TextView textViewName;
    public SwitchCompat mySwitch;


    public ViewHolder(View itemView) {
        super(itemView);


        textViewName = (TextView) itemView.findViewById(R.id.textViewName);
        mySwitch = (SwitchCompat) itemView.findViewById(R.id.switchbtn);

    }
}

}
Janki Gadhiya
  • 4,492
  • 2
  • 29
  • 59

2 Answers2

1

First, create your adapter in your onCreate method and keep it :

mAdapter = new CardView(getActivity());
recyclerView.setAdapter(mAdapter);

Create a new method on your adapter to update data, like :

mAdapter.updateItems(...);

Finally, when you get response from your service, you just need to call the updateItems method and to notify changes with

mAdapter.notifyDataSetChanged();

Hope this helps!

Johann67
  • 385
  • 6
  • 16
0

You have to set tag for your switch inside BindViewHolder to findout which item has been clicked for update the list items.

**holder.mySwitch.setTag(position);**

After that once you got volley response update your ItemList

 holder.mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

          **final CompoundButton mySwitch=buttonView;**
                StringRequest stringRequest = new StringRequest(Request.Method.POST,POST_SWITCH_URL ,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String s) {

                                Toast.makeText(context, s, Toast.LENGTH_LONG).show();
                           //Got success response from volley

 **int sPosition=mySwitch.getTag();
items.get(sPosition).setItem("YOUR TEXT");
notifyDataSetChanged();**


                            }
                        },
                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError volleyError) {


                                //Showing toast
                                Toast.makeText(context, "error to connect", Toast.LENGTH_LONG).show();
                            }
                        }) {
                    @Override
                    protected java.util.Map<String, String> getParams() throws AuthFailureError {

                        Map<String, String> params = new Hashtable<String, String>();
                        final String control = "0";

                        params.put("device",device);
                        params.put("control",control);




                        return params;
                    }
                };

                //Creating a Request Queue
                RequestQueue requestQueue = Volley.newRequestQueue(context);

                //Adding request to the queue
                requestQueue.add(stringRequest);

            }
        });
dindinii
  • 645
  • 4
  • 7