1

multiple items get selected automatically when i select one item in recyclerview

What i m doing is

i just want to fetch contacts with no duplication and list all contacts in recyclerview And make visible two textviews (one is for number and second is for name)Its Done But The problem is

when i click on an item it gets clicked 4 times (for example if i click on an item it make visible two textviews but the same item with same name and number get visible like with i have clicked 4 items and see pics )

adpter class

    package "";

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SwitchCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.altu.calllocker.R;
import com.example.altu.calllocker.model.ContactsModel;

import java.util.HashMap;
import java.util.List;


public class ContactsAdapter extends RecyclerView.Adapter<ContactsAdapter.ContactsViewHolder> {
    List<ContactsModel> list;
    Context context;
    public static HashMap<String, String> hashMapBlock;

    public ContactsAdapter(List<ContactsModel> list, Context context) {
        this.list = list;
        this.context = context;
    }

    @Override
    public ContactsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.contacts_item, parent, false);
        context = parent.getContext();
        hashMapBlock = new HashMap<>();
        ContactsViewHolder viewHolder = new ContactsViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(final ContactsViewHolder holder, final int position) {
        holder.txtno.setText(list.get(position).get_id());
        holder.txt_contactname.setText(list.get(position).getDisplay_name());
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e("position", list.get(position).get_id() + "  " + list.get(position).getData1() + "  " + list.get(position).getDisplay_name());
                if (holder.linearLayout.getVisibility() == View.VISIBLE) {
                    holder.linearLayout.setVisibility(View.GONE);
                } else {
                    holder.linearLayout.setVisibility(View.VISIBLE);
                    holder.txt_contactName.setText(list.get(position).getDisplay_name());
                    holder.txt_contact_no.setText(list.get(position).getData1());
                }

            }
        });
        holder.switchBlock.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    hashMapBlock.put(list.get(position).getData1(), "block");
                    Log.e("block", list.get(position).getData1());
                    Toast.makeText(context, "block" + "  " + list.get(position).getData1(), Toast.LENGTH_SHORT).show();
                } else {
                    hashMapBlock.remove(list.get(position).getData1());
                    Log.e("unblock", list.get(position).getData1());
                    Toast.makeText(context, "unblock" + "  " + list.get(position).getData1(), Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

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

    public class ContactsViewHolder extends RecyclerView.ViewHolder {
        TextView txt_contactname;
        TextView txt_contactName;
        TextView txt_contact_no;
        LinearLayout linearLayout;
        SwitchCompat switchBlock;
        TextView txtno;

        public ContactsViewHolder(View itemView) {

            super(itemView);
            this.txtno = (TextView) itemView.findViewById(R.id.txtno);
            this.txt_contactname = (TextView) itemView.findViewById(R.id.txt_contactName);
            this.txt_contactName = (TextView) itemView.findViewById(R.id.txt_contact_name);
            this.txt_contact_no = (TextView) itemView.findViewById(R.id.txt_contact_no);
            this.linearLayout = (LinearLayout) itemView.findViewById(R.id.linearlayout);
            this.switchBlock = (SwitchCompat) itemView.findViewById(R.id.switchButton_block);


        }
    }
}

MainActivity where i get all contacts to recyclerview

 package "";

import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.AsyncTask;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.Toast;

import com.example.altu.calllocker.R;
import com.example.altu.calllocker.adapter.ContactsAdapter;
import com.example.altu.calllocker.customclass.SimpleDividerItemDecoration;
import com.example.altu.calllocker.model.ContactsModel;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    RecyclerView recyclerview_contacts;
    List<ContactsModel> contactVOList;
    ProgressDialog progressDialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bindview();
        new Thread(new Task()).start();
        progressDialog.dismiss();


        //adapter = new ContactsAdapter(contactlist, getApplicationContext());
        //recyclerview_contacts.setAdapter(adapter);

    }

    public void bindview() {
        recyclerview_contacts = (RecyclerView) findViewById(R.id.recyclerview_contacts);
        contactVOList = new ArrayList<>();
        recyclerview_contacts.setHasFixedSize(true);
        LinearLayoutManager llm = new LinearLayoutManager(MainActivity.this);
        llm.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerview_contacts.setLayoutManager(llm);
        SimpleDividerItemDecoration itemDecoration = new SimpleDividerItemDecoration(this);
        recyclerview_contacts.addItemDecoration(itemDecoration);
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Loading.....");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMax(100);
        progressDialog.setProgress(0);
        progressDialog.show();
    }

    class Task implements Runnable {
        @Override
        public void run() {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    getAllContact();
                }
            });


        }

    }



    private void getAllContact() {
        if (contactVOList.size() > 0) {
            contactVOList.clear();
        }
        //  List<ContactsModel> contactVOList = new ArrayList();
        ContactsModel contactVO;

        ContentResolver contentResolver = getContentResolver();
        Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
        if (cursor.getCount() > 0) {
            while (cursor.moveToNext()) {

                int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
                if (hasPhoneNumber > 0) {
                    String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                    String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

                    contactVO = new ContactsModel();
                    contactVO.setDisplay_name(name);
                    contactVO.set_id(id);

                    Cursor phoneCursor = contentResolver.query(
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                            null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                            new String[]{id},
                            null);
                    if (phoneCursor.moveToNext()) {
                        String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        contactVO.setData1(phoneNumber);
                    }

                    phoneCursor.close();

                    Cursor emailCursor = contentResolver.query(
                            ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                            null,
                            ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
                            new String[]{id}, null);
                    while (emailCursor.moveToNext()) {
                        String emailId = emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
                    }
                    emailCursor.close();
                    contactVOList.add(contactVO);
                }

            }

            ContactsAdapter contactAdapter = new ContactsAdapter(contactVOList, getApplicationContext());
            //recyclerview_contacts.setLayoutManager(new LinearLayoutManager(this));
            recyclerview_contacts.setAdapter(contactAdapter);
            contactAdapter.notifyDataSetChanged();
            Log.e("size", String.valueOf(contactVOList.size()));
        }
    }

}

image 1 image2 with auto selection

  • Check this: [link](http://stackoverflow.com/questions/32427889/checkbox-in-recyclerview-keeps-on-checking-different-items) – Skullper Nov 04 '16 at 11:13
  • try to hold the clicked state of that item and then notifyDataSetChanged(); – Rushi Ayyappa Nov 04 '16 at 11:16
  • @PavliukR it isn't related to my problem ... –  Nov 04 '16 at 11:17
  • @RushiAyyappa any a single line code hint? –  Nov 04 '16 at 11:17
  • maintain a boolean variable isClicked in model..after selecting an item arraylist.get(clickedposition).setisChecked=true; then call notifyDataSetChanged(); – Rushi Ayyappa Nov 04 '16 at 11:20
  • @RushiAyyappa check update question title its about to clicking not about selecting –  Nov 04 '16 at 11:23
  • the thing is in recyclerview all the item positions get zigzagged because onBind method keeps called all the time.hence to control this we should maintain the state of the selected items.now the answer i gave you will work for both item as wel row.. and you select an item by a click right? – Rushi Ayyappa Nov 04 '16 at 11:27

1 Answers1

1

You should set OnclickListener inside ViewHolder and get clicked Item's posision with getLayoutPosition() method.

 public class ContactsViewHolder extends RecyclerView.ViewHolder {
    TextView txt_contactname;
    TextView txt_contactName;
    TextView txt_contact_no;
    LinearLayout linearLayout;
    SwitchCompat switchBlock;
    TextView txtno;

    public ContactsViewHolder(View itemView) {

        super(itemView);
        this.txtno = (TextView) itemView.findViewById(R.id.txtno);
        this.txt_contactname = (TextView) itemView.findViewById(R.id.txt_contactName);
        this.txt_contactName = (TextView) itemView.findViewById(R.id.txt_contact_name);
        this.txt_contact_no = (TextView) itemView.findViewById(R.id.txt_contact_no);
        this.linearLayout = (LinearLayout) itemView.findViewById(R.id.linearlayout);
        this.switchBlock = (SwitchCompat) itemView.findViewById(R.id.switchButton_block);

        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                 int position =getLayoutPosition();
                //Your logic

            }
        });


    }
}
Vygintas B
  • 1,624
  • 13
  • 31