How to get element of listview row using getChildAt

332 views Asked by At

I have a custom view (which has checkbox) for listview. I also added a checkbox in activity layout to select all checkboxes. I'm getting all the listview items when I select the activity checkbox but I'm unable to make all the checkboxes in listview as checked. When I tried to use getChildAt() in for loop, I'm getting a Null Pointer .

// row layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:id="@+id/rootlay">

    <CheckBox
        android:id="@+id/cbBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical" >
    </CheckBox>

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:orientation="vertical"
        android:layout_weight="1" >

        <TextView
            android:id="@+id/tvDescr"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:text=""
            android:textSize="20sp" >
        </TextView>

        <TextView
            android:id="@+id/tvPrice"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:text="" >
        </TextView>
    </LinearLayout>


</LinearLayout>
public class ContactsPickerActivity extends AppCompatActivity{

    ArrayList<Model> arrayList = new ArrayList<>();
    ListView list;
    CustomAdapter adapter;
    CheckBox selectall;

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

        list = (ListView)findViewById(R.id.list);
        Button loadbtn = (Button)findViewById(R.id.loadbtn);
        loadbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ){
                    askForPermission(Manifest.permission.READ_CONTACTS,1100);
                }else{
                    new LoadContactsAyscn().execute();
                }

            }
        });

        Button getbtn = (Button)findViewById(R.id.getbtn);
        getbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String result = "Selected Product are :";
                for (Model p : adapter.getBox()) {
                    if (p.box){
                        result += "\n" + p.price;
                    }
                }
                Toast.makeText(ContactsPickerActivity.this, result, Toast.LENGTH_LONG).show();
            }
        });

        adapter = new CustomAdapter(ContactsPickerActivity.this, arrayList);
        list.setAdapter(adapter);

        selectall = (CheckBox)findViewById(R.id.selectall);
        selectall.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if(b){
                    int count = list.getAdapter().getCount();
                    System.out.println("sammy_total_count "+count);
                    for(int i=0; i<count; i++){
                        adapter.getProduct(i).box=true;
                        LinearLayout itemlay = (LinearLayout)list.getChildAt(i);
                        CheckBox checkBox = (CheckBox)itemlay.findViewById(R.id.cbBox);
                        checkBox.setTag(i);
                        checkBox.setChecked(adapter.getProduct(i).box);
                    }
                }else{
                    int count = list.getAdapter().getCount();
                    System.out.println("sammy_total_count "+count);
                    for(int i=0; i<count; i++){
                        adapter.getProduct(i).box=false;
                        LinearLayout itemlay = (LinearLayout)list.getChildAt(i);
                        CheckBox checkBox = (CheckBox)itemlay.findViewById(R.id.cbBox);
                        checkBox.setTag(i);
                        checkBox.setChecked(adapter.getProduct(i).box);
                    }
                }

            }
        });
    }

    private void askForPermission(String permission, Integer requestCode) {
        System.out.println("sammy_reached_askForPermission");
        if (ContextCompat.checkSelfPermission(ContactsPickerActivity.this, permission) != PackageManager.PERMISSION_GRANTED) {

            if(ActivityCompat.shouldShowRequestPermissionRationale(ContactsPickerActivity.this, permission)) {
                // if (shouldShowRequestPermissionRationale(permission)) {  // for fragment

                ActivityCompat.requestPermissions(ContactsPickerActivity.this, new String[]{permission}, requestCode);
                // requestPermissions(new String[]{permission}, requestCode);  // for fragment

            } else {

                ActivityCompat.requestPermissions(ContactsPickerActivity.this, new String[]{permission}, requestCode);
                // requestPermissions(new String[]{permission}, requestCode); // for fragment
            }
        } else {
            new LoadContactsAyscn().execute();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        System.out.println("sammy_reached_onRequestPermissionsResult");
        if(ActivityCompat.checkSelfPermission(ContactsPickerActivity.this, permissions[0]) == PackageManager.PERMISSION_GRANTED){
            if(requestCode==1100){
                new LoadContactsAyscn().execute();
            }
            Toast.makeText(ContactsPickerActivity.this, "Permission granted", Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(ContactsPickerActivity.this, "Permission denied", Toast.LENGTH_SHORT).show();
        }
    }

    class LoadContactsAyscn extends AsyncTask<Void, Void, ArrayList<Model>> {
        ProgressDialog pd;

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();

            pd = ProgressDialog.show(ContactsPickerActivity.this, "Loading Contacts",
                    "Please Wait");
        }

        @Override
        protected ArrayList<Model> doInBackground(Void... params) {


            Cursor c = getContentResolver().query(
                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                    null, null, null);
            while (c.moveToNext()) {

                String contactName = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                String phNumber = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));


                arrayList.add(new Model(contactName,phNumber, false));

            }
            c.close();

            return arrayList;
        }

        @Override
        protected void onPostExecute(ArrayList<Model> contacts) {
            // TODO Auto-generated method stub
            super.onPostExecute(contacts);

            pd.cancel();
            adapter.notifyDataSetChanged();


        }

    }
}
3

There are 3 answers

0
oyenigun On

I think you should change "box" property in your models and use notifyDataSetChanged().

ListView will be refreshed and the CheckBoxes will be updated by your boolean field.

4
Exigente05 On

Change like this,

for(int i=0; i<count; i++){
                    adapter.getProduct(i).box=true;
                    View rowView = list.getChildAt(i);
                    LinearLayout itemlay = (LinearLayout)rowView.findViewById(R.id.id);
                    CheckBox checkBox = (CheckBox)rowView.findViewById(R.id.cbBox);
                    checkBox.setTag(i);
                    checkBox.setChecked(adapter.getProduct(i).box);
                }

Here is an issue of visible items and total items. NPE is getting because not all items are in view. So you need to change like this,

for(int i=0; i<count; i++){
                    adapter.getProduct(i).box=true;
                    notifyDataSetChanged();
                }

And inside list adapter getView() method

checkBox.setChecked(adapter.getProduct(i).box);

Make sure getProduct(i).box value is not null

0
Mr.Popular On

Better you can define one

      ArrayList<ViewHolder> holders = new ArrayList<>();

and in your adapter just add your holders into list like

          holders.add(holder);

and whenever you are pressing checkbox just get the holder and get the checkbox and set the checkbox state like following

  (holders.get(POSITION)).checkbox.setChecked(boolean);

it ll be simple and easy one to do....

Hope it helps!!!