Android tutorial

Android How get list of checked checkboxes from recyclerview android

checked checkboxes from recyclerview android
checked checkboxes from recyclerview android

Hi everyone today I am discussing How to get list of checked checkboxes from recyclerview android. In this android tutorial, I solve this problem.

  • Android how to used recycler view list in android.
  • how to add checkbox in recycler view.
  •  Get the value of a selected item in the recycler view list.
  • how to Add multiple checkbox checked value.
  • and send the value to server with JSON API  using volley

For a Recycler View to work fine, you need to set an Adapter and that Adapter in turns calls the ViewHolder class and you override the” onBindViewHolder ” method of the Adapter to bind the view.

hare I am using API for show data in recycler view list and, select a multiple checkbox and get the value with string builder used forget array value to sting and send to the server. there is an easy way to get the select all checkboxes value in RecyclerView.

How to get a list of checked checkboxes from recyclerview android.

Step 1: Start Android Studio and Create a Project in your Android studio

Setp2:-  Create an Activity Uplode_Reg_Photo

Step 3:- Open your Manifest file and add user permission

<uses-permission android:name=“android.permission.INTERNET” />
<uses-permission android:name=“android.permission.ACCESS_NETWORK_STATE” />
<uses-permission android:name=“android.permission.WRITE_EXTERNAL_STORAGE” />
<uses-permission android:name=“android.permission.READ_EXTERNAL_STORAGE” />

Step4:- add the dependency in your build.gradle

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:27.+'
    compile 'com.android.support:design:27.+'
    compile 'com.android.support:support-v4:27.+'
    compile 'de.hdodenhof:circleimageview:2.1.0'
    compile 'com.android.support:cardview-v7:27.+'
    compile 'com.android.support:recyclerview-v7:27.+'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.android.volley:volley:1.0.0'
    compile 'com.android.support:support-vector-drawable:27.+'
    compile 'com.github.chrisbanes:PhotoView:2.1.3'
    testCompile 'junit:junit:4.12'
}

after adding these sync your project and wait for finish.

Step 5:- Open you activity XML file and add recycler view list

<android.support.v7.widget.RecyclerView
    android:id="@+id/Recycler_List"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1" />
<Button
    android:id="@+id/btnShowCheckedItems"
    android:layout_width="150dp"
    android:layout_height="wrap_content"
    android:layout_margin="10dp"
    android:layout_gravity="center"
    android:textAppearance="?android:textAppearanceMedium"
    android:background="@drawable/button_left"
    android:textColor="@color/white"
    android:text="Submit"/>

in your XML file add recycler view layout and a button layout.

Step 6: Create an XML file  CardView for item layout for recycler list

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/tools"
    android:id="@+id/card_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="5dp"
    card_view:cardBackgroundColor="@color/white"
    android:layout_marginRight="5dp"
    android:layout_marginLeft="5dp"
    card_view:cardCornerRadius="5dp"
    app:ignore="NamespaceTypo">

    <LinearLayout
        android:id="@+id/rlInner"
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:padding="5dp"
        android:layout_height="match_parent" >
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="vertical">
            <TextView
                android:id="@+id/tvContent"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textStyle="bold"
                android:padding="5dp"
                android:text="Medium Text"
                android:textColor="#000000" />

            <TextView
                android:id="@+id/tvContentId"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text=""
                android:visibility="gone"
                android:textColor="#000000" />

            <TextView
                android:id="@+id/tvDescription"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="test"
                android:inputType="textMultiLine"
                android:padding="5dp"
                android:textColor="#000000"
                />
        </LinearLayout>
        <CheckBox
            android:id="@+id/chbContent"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="10dp" />

    </LinearLayout>


</android.support.v7.widget.CardView>

in item view layout you can add checkbox text view for showing the date

Step 7: Open your java file and add these code.

in your java file, you implement XML layout and get data for API and show data in recycler list using adapter class to get the value and set the value.

 

public class Add_Exercise extends AppCompatActivity implements View.OnClickListener {
  
    public static final String KEY_ExerciseId = "exerciseId";
  
    RecyclerView mListView;
    String arrayData="",time="";
    ApproveRecyclerView approveRecyclerView=new ApproveRecyclerView(this);
    ArrayList<String> arrayListUser=new ArrayList<>();
    Button btnShowCheckedItems;
    public static ArrayList<DataObject> approvePendingDataArrayList=new ArrayList<>();
    TextView SelcetTime;
    public static String EMAIL;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add__exercise);
        btnShowCheckedItems = (Button) findViewById(R.id.btnShowCheckedItems);
        btnShowCheckedItems.setOnClickListener(this);
        mListView= (RecyclerView) findViewById(R.id.Recycler_List);
      
          init();
      

        android.support.v7.app.ActionBar actionBar = getSupportActionBar();
        actionBar.setHomeButtonEnabled(true);
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setTitle("Recycler View  ");
    }

 

Create a method to getting a response from API. and show in list 

 private void init() {
        // progress Dialog
        final ProgressDialog loading = new ProgressDialog(Add_Exercise.this);
        loading.setMessage("Please Wait...");
        loading.show();
// json response code
        StringRequest stringRequest = new StringRequest(Request.Method.POST, ConfiURL.All_Exercise_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        try {
                            Log.d("JSON", response);
                            loading.dismiss();
                            JSONObject jsonObject = new JSONObject(response);
                            JSONArray jArray = jsonObject.getJSONArray("allData");
                            if (jArray.length() == 0) {
                                /*of array length is 0 then show alert dialog if
                                 * array is not 0 then go else*/
                            } else {
                                approvePendingDataArrayList.clear();
                                for (int i = 0; i < jArray.length(); i++) {
                                    final DataObject approvePending_data = new DataObject();
                                    JSONObject jsonObject1 = jArray.getJSONObject(i);
                                    approvePending_data.setmText1(jsonObject1.getString("id"));
                                    approvePending_data.setmText2(jsonObject1.getString("name"));
                                    approvePending_data.setmText3(jsonObject1.getString("description"));
                                    approvePendingDataArrayList.add(approvePending_data);

                                }
                                mListView.setLayoutManager(new LinearLayoutManager(Add_Exercise.this));
                                mListView.setAdapter(approveRecyclerView);
                            }
                        } catch (Exception e) {
                            Log.d("Tag", e.getMessage());

                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        loading.dismiss();
                        if (error instanceof TimeoutError || error instanceof NoConnectionError) {
                            ContextThemeWrapper ctw = new ContextThemeWrapper( Add_Exercise.this, R.style.Theme_AlertDialog);
                            final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ctw);
                            alertDialogBuilder.setTitle("No Connection");
                            alertDialogBuilder.setMessage(" Network timeout  error please try again ");
                            alertDialogBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {

                                }
                            });
                            alertDialogBuilder.show();
                        }
                          
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                return map;
            }
        };

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }

 

Step 8: Create an Adapter class for show recycler view list data and used item OnClickLIstner.

//hare is exercise recyclerView List Adupter for multi item select

  public class ApproveRecyclerView extends RecyclerView.Adapter<ApproveRecyclerView.sViewHolder> {
      Context context;

      public ApproveRecyclerView(Context context) {
          this.context = context;
      }

      @Override
      public ApproveRecyclerView.sViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
          return new sViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.row, parent, false));
      }

      @Override
      public void onBindViewHolder(final ApproveRecyclerView.sViewHolder holder, final int position) {
          final DataObject approvePendingData = approvePendingDataArrayList.get(position);
          holder.tvname.setText(approvePendingData.getmText2());
          holder.dealerid=approvePendingDataArrayList.get(position).getmText1();
          holder.tvDescription.setText(approvePendingData.getmText3());

          //===========click listner of check box===============//

          holder.checkBoxparent.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View arg0) {
                  final boolean isChecked = holder.checkBoxparent.isChecked();
                  for (int i=0; i<approvePendingDataArrayList.size();i++) {
                      if (isChecked) {
                          if (!arrayListUser.contains(approvePendingDataArrayList.get(position).getmText1()))
                              arrayListUser.add(i, approvePendingDataArrayList.get(position).getmText1());
                          arrayData=arrayListUser.toString().replace("[", "").replace("]", "").trim();
                      } else {
                          arrayListUser.remove(approvePendingDataArrayList.get(position).getmText1());
                          arrayData=arrayListUser.toString().replace("[", "").replace("]", "").trim();
                      }
                  }
              }
          });
      }

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

      class sViewHolder extends RecyclerView.ViewHolder {
          TextView tvred, tvDescription, tvcedar, tveasy, tvexcel,tvname,tvplus,tvsparkle;
          CheckBox checkBoxparent;
          RadioGroup radioGroup;
          String dealerid;

          public sViewHolder(View itemView) {
              super(itemView);
              tvname = (TextView) itemView.findViewById(R.id.tvContent);
              tvred = (TextView) itemView.findViewById(R.id.tvContentId);
              checkBoxparent = (CheckBox) itemView.findViewById(R.id.chbContent);
              tvDescription=(TextView)itemView.findViewById(R.id.tvDescription);

          }

      }
  }

this is running fine and get the value for selected checkbox store on in a single string

holder.checkBoxparent.setOnClickListener using this method