jeudi 27 mai 2021

Get list of all check checkboxes of recyclerview on button click of layout to next activity in android

I am beginner to android development and I want to create a small module which displays contact list along with checkbox. Select particular contact and display its respective sms only. I have populated the recyclerView with contact list and checkbox. Problem = Button is created on layout and not on recyclerView. How to get list of all check checkboxes data of recyclerview on button click (onClick = onContactSave()) which is part of ContactActivity to next activity ContactConfirmActivity. Got stuck onContactSave() to get checkbox data of recyclerView.

1.ContactModel

public class ContactModel {
    String name,number;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }


    private boolean isSelected;

    public boolean isSelected() {
        return isSelected;
    }

    public void setSelected(boolean selected) {
        isSelected = selected;
    }
}

2.item_contact.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto">


    <ImageView
        android:id="@+id/iv_image"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:src="@drawable/ic_person"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        app:layout_constraintStart_toEndOf="@id/iv_image"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent">

        <TextView
            android:id="@+id/tv_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="18sp"
            android:textStyle="bold"
            android:textColor="@color/purple_700"
            android:paddingTop="8dp"
            android:paddingBottom="8dp"/>

        <TextView
            android:id="@+id/tv_number"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="14sp"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent">

        <CheckBox
            android:id="@+id/ch_contact"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

3.activity_contact.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ContactActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:listitem="@layout/item_contact"/>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="10dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp">


        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:onClick="onContactSave"
            android:text="Save"
            android:textColor="@android:color/white"
            android:textStyle="bold" />
    </RelativeLayout>

</RelativeLayout>

4.ContactAdapter

package com.example.myapplication;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.ViewHolder> {
    Activity activity;
    ArrayList<ContactModel> arrayList;

    public interface Listener {
        public void onClick(int index);
    }

    private final Listener listener;

    public ContactAdapter(Activity activity, ArrayList<ContactModel> arrayList,Listener listener) {
        this.activity = activity;
        this.arrayList = arrayList;
        this.listener = listener;
        notifyDataSetChanged();
    }

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

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        if (arrayList != null) {
            holder.recycler_checkbox.setOnCheckedChangeListener(null);
            holder.tvName.setText(arrayList.get(position).getName());
            holder.tvNumber.setText(arrayList.get(position).getNumber());
            holder.recycler_checkbox.setChecked(arrayList.get(position).isSelected());
            holder.recycler_checkbox.setTag(arrayList.get(position));
            holder.recycler_checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                        arrayList.get(position).setSelected(true);
                        listener.onClick(position);
                        Toast.makeText(activity,
                                "Checked : " + arrayList.get(position).getName()
                                , Toast.LENGTH_LONG).show();
                    } else {
                        arrayList.get(position).setSelected(false);
                        Toast.makeText(activity,
                                "Unchecked : " + arrayList.get(position).getName()
                                , Toast.LENGTH_LONG).show();

                    }
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return (arrayList == null) ? 0 : arrayList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        TextView tvName,tvNumber;
        public CheckBox recycler_checkbox;

        public ViewHolder(@NonNull  View itemView) {
            super(itemView);
            tvName = itemView.findViewById(R.id.tv_name);
            tvNumber = itemView.findViewById(R.id.tv_number);
            recycler_checkbox = itemView.findViewById(R.id.ch_contact);

        }
    }
}

5.ContactActivity

package com.example.myapplication;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.Toast;

import java.util.ArrayList;

public class ContactActivity extends AppCompatActivity implements ContactAdapter.Listener{

    RecyclerView recyclerView;
    ArrayList<ContactModel> arrayList = new ArrayList<ContactModel>();
    ContactAdapter adapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact);

        recyclerView = findViewById(R.id.recycler_view);

        checkPermission();
    }

    private void checkPermission() {
        if(ContextCompat.checkSelfPermission(ContactActivity.this, Manifest.permission.READ_CONTACTS) !=
                PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(ContactActivity.this,new String[]{Manifest.permission.READ_CONTACTS},100);
        }else {
            getContactList();
        }
    }

    private void getContactList() {
        Uri uri = ContactsContract.Contacts.CONTENT_URI;
        String sort = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC";
        Cursor cursor = getContentResolver().query(uri,null,null,null,sort);
        if(cursor.getCount() > 0){
            while (cursor.moveToNext()){
                String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                Uri uriPhone = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
                String selection= ContactsContract.CommonDataKinds.Phone.CONTACT_ID+" =?";
                Cursor phoneCursor = getContentResolver().query(uriPhone,null,selection,new String[]{id},null);
                if(phoneCursor.moveToNext()){
                    String number = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    ContactModel model = new ContactModel();
                    model.setName(name);
                    model.setNumber(number);
                    arrayList.add(model);
                    phoneCursor.close();
                }
            }
            cursor.close();
        }
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new ContactAdapter(this,arrayList, this);
        recyclerView.setAdapter(adapter);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull  int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == 100 && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
            getContactList();
        }else {
            Toast.makeText(ContactActivity.this, "Permission Denied.", Toast.LENGTH_SHORT).show();
            checkPermission();
        }
    }

    public void onContactSave(View view) {
        Intent contactConfirmIntent = new Intent(this,ContactConfirmActivity.class);
        //contactConfirmIntent.putExtra("Name",contactModel.getName());
        startActivity(contactConfirmIntent);

    }

    @Override
    public void onClick(int index) {

    }
}
  1. activity_contact_confirm.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ContactConfirmActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:text=""
        android:id="@+id/tv"/>

    <Button
        android:id="@+id/btnDisplaySMS"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Display SMS"
        android:textAllCaps="false"
        android:layout_alignParentBottom="true"
        android:onClick="onDisplaySMS"/>

</RelativeLayout>

7.ContactConfirmActivity

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class ContactConfirmActivity extends AppCompatActivity {

    private TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact_confirm);

        Intent intent = getIntent();
        String message = intent.getStringExtra("Name");
        TextView textView = findViewById(R.id.tv);
        textView.setText(message);

    }

    public void onDisplaySMS(View view) {
        Intent displaySMSIntent = new Intent(this,ListViewSMSActivity.class);
        startActivity(displaySMSIntent);
    }
}



Aucun commentaire:

Enregistrer un commentaire