List view with Check box Using Custom Adapter class

List view is Great and useful component of Android Application. I have already tech you Simple List view with custom adapter class. you can learn about Custom Adapter Class from that tutorial. you can combine many components like Text View , Check Box, Image View, Image Button etc. and can make List view as you require. so Today i am gone create List view with custom layout which consist of Text view and Check box.

There is an issue with list view when you are using check box within list view is that the checked state of check box will not maintain by android because when you scroll list view it will generate new view for each row using getView() method and garbage collector will remove all above View to make space so check box state will also destroy or garbage by garbage collector. but don't worry i have solved that problem and make this tutorial for you so you can use it.
Main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dp">


    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentTop="true"
        android:divider="#000"
        android:dividerHeight="0.8dp"/>

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:text="Check Selected"/>

</RelativeLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:descendantFocusability="blocksDescendants">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginTop="10dp"
        android:singleLine="true"
        android:ellipsize="end"
        android:maxLines="1"
        android:padding="5dp"
        android:text="Medium Text"
        android:textAppearance="?android:attr/textAppearanceMedium"/>

    <CheckBox
        android:id="@+id/checkBox1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/textView1"
        android:layout_alignParentRight="true"
        android:layout_marginRight="15dp"
        android:focusable="false"
        android:focusableInTouchMode="false"/>

</RelativeLayout>

Main.java
package com.androprogrammer.app1;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import android.app.Activity;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class Main extends Activity implements OnItemClickListener{

 ListView apps;
 PackageManager packageManager;
 ArrayList <String> checkedValue;
 Button bt1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        bt1 = (Button) findViewById(R.id.button1);
        apps = (ListView) findViewById(R.id.listView1);
        packageManager = getPackageManager();
  final List <PackageInfo> packageList = packageManager
    .getInstalledPackages(PackageManager.GET_META_DATA); // all apps in the phone
  final List <PackageInfo> packageList1 = packageManager
    .getInstalledPackages(0);

    try {
      packageList1.clear();
      for (int n = 0; n < packageList.size(); n++) 
      {

       PackageInfo PackInfo = packageList.get(n);
       if (((PackInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) != true) 
        //check weather it is system app or user installed app
       {
        try 
        {
         
          packageList1.add(packageList.get(n)); // add in 2nd list if it is user installed app 
           Collections.sort(packageList1,new Comparator <PackageInfo>() 
             // this will sort App list on the basis of app name
           {
            public int compare(PackageInfo o1,PackageInfo o2) 
            {
             return o1.applicationInfo.loadLabel(getPackageManager()).toString()
               .compareToIgnoreCase(o2.applicationInfo.loadLabel(getPackageManager())
                   .toString());// compare and return sorted packagelist.
            }
           });
           
         
        } catch (NullPointerException e) {
         e.printStackTrace();
        }
       }
      }
     } catch (Exception e) {
      e.printStackTrace();
     }
    Listadapter Adapter = new Listadapter(this,packageList1, packageManager);
    apps.setAdapter(Adapter);
    apps.setOnItemClickListener(this);
    bt1.setOnClickListener(new View.OnClickListener() {
     
     @Override
     public void onClick(View v) {
      // TODO Auto-generated method stub
      Toast.makeText(Main.this,"" + checkedValue,Toast.LENGTH_LONG).show();
     }
    });
        
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }


 @Override
 public void onItemClick(AdapterView arg0, View v, int position, long arg3) {
  // TODO Auto-generated method stub
  CheckBox cb = (CheckBox) v.findViewById(R.id.checkBox1);
  TextView tv = (TextView) v.findViewById(R.id.textView1);
  cb.performClick();
  if (cb.isChecked()) {
   
   checkedValue.add(tv.getText().toString());
  } else if (!cb.isChecked()) {
   checkedValue.remove(tv.getText().toString());
  }

   
  
 }
    
}
Listadapter.java
package com.androprogrammer.app1;

import java.util.List;

import android.app.Activity;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;

public class Listadapter extends BaseAdapter{

 List <PackageInfo> packageList;
 Activity context;
 PackageManager packageManager;
 boolean[] itemChecked;

 public Listadapter(Activity context, List <PackageInfo> packageList,
   PackageManager packageManager) {
  super();
  this.context = context;
  this.packageList = packageList;
  this.packageManager = packageManager;
  itemChecked = new boolean[packageList.size()];
 }

 private class ViewHolder {
  TextView apkName;
  CheckBox ck1;
 }

 public int getCount() {
  return packageList.size();
 }

 public Object getItem(int position) {
  return packageList.get(position);
 }

 public long getItemId(int position) {
  return 0;
 }

 @Override
 public View getView(final int position, View convertView, ViewGroup parent) {
  final ViewHolder holder;
  
  LayoutInflater inflater = context.getLayoutInflater();

  if (convertView == null) {
   convertView = inflater.inflate(R.layout.list_item, null);
   holder = new ViewHolder();

   holder.apkName = (TextView) convertView
     .findViewById(R.id.textView1);
   holder.ck1 = (CheckBox) convertView
     .findViewById(R.id.checkBox1);

   convertView.setTag(holder);

  } else {
   
   holder = (ViewHolder) convertView.getTag();
  }

  PackageInfo packageInfo = (PackageInfo) getItem(position);

  Drawable appIcon = packageManager
    .getApplicationIcon(packageInfo.applicationInfo);
  String appName = packageManager.getApplicationLabel(
    packageInfo.applicationInfo).toString();
  appIcon.setBounds(0, 0, 40, 40);
  holder.apkName.setCompoundDrawables(appIcon, null, null, null);
  holder.apkName.setCompoundDrawablePadding(15);
  holder.apkName.setText(appName);
  holder.ck1.setChecked(false);

  if (itemChecked[position])
   holder.ck1.setChecked(true);
  else
   holder.ck1.setChecked(false);

  holder.ck1.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    if (holder.ck1.isChecked())
     itemChecked[position] = true;
    else
     itemChecked[position] = false;
   }
  });

  return convertView;

 }



}


Screen Shots

List view with Check box
  List view with Check box

In this project i am not concern about design of layout. you can explore or style it as you require. in the above project i have taken boolean array which stores Status of check box weather it is checked or not. when user click on List view Item it will call Perfom Click method of check box which is equal to call onclick of check box. And on button click i have called Toast message with all checked item of the list.

I have taken Packagelist as list view item but you can take any value like String, integer or both. i hope this will help you. if you have any error or query then comment in below comment box.
Keep coding...

Download Code

44 comments :

  1. Thank you for the tutorial, it is helpful. But I would like to point out an issue for those who may want to use this. The list_item.xml has a problem. The Checkbox is inside the TextView - which is not correct. It should be as below.

    Another detail to note, esp for those who are trying to copy paste from this tutorial, is that the attributes in the xml files are not correct as per case sensitivity goes. For example - "layout_marginTop" is written as "layout_margintop"












    ReplyDelete
    Replies
    1. Hey thanks for pointing that mistakes but it is b'z of these code snippet. It won't give me any error in my eclipse and android studio.
      I will update the code.
      It have no error at all so just try it.

      Delete
  2. hey wasim thanks man for check box solution.
    you save my days googling.
    and it works perfect i have checked it in my app.

    ReplyDelete
    Replies
    1. Its my pleasure Robert..
      I hope other tutorials also helpful to you...

      Delete
    2. how to save this check box value in same activity

      Delete
  3. how save this check box value when we go next activity.

    ReplyDelete
    Replies
    1. Surender
      I have stored checked value in main file .
      In onItemClick method see I have stored value in checkedValue array.
      So you can get value in same and other activity.

      Delete
  4. but when am go next activity and than back than all check box are unchecked. how can i save check box value

    ReplyDelete
    Replies
    1. hey surender,
      That is b'z of when you start list activity again it initalize that array (itemChecked) and that's why it became clear (null). if you want to store that value then you have to put conditions like this
      if(itemChecked != null) then pass those value to list view. i have not done such things.
      so this is just idea how you can do that thing. the above code is solution for bug :
      when you scroll list view then the above one checked items get unchecked b'z garbage collector remove those row object and create new for display the new values.
      so to over come this problem i had taken that array.
      i hope now you understand what this tutorial about and how it works.

      Delete
  5. i am getting values in checkbox,but when i try to scroll down this list.previous choice goes,is there any solution?

    ReplyDelete
    Replies
    1. Hey ashish ,
      Recheck the code weather you have same code or not. b'z this code is for same issue and its working perfectly.
      If you find again this problem let me know I will check it and send you full zip file..

      Delete
  6. Hi u r code is help to me.But am plan to develope and application like listwith item and checkbox and data from the database.in list view when i check any of the check box store that item as checked in db and when go back and come to here i can show this as checked on like gmail set as favourate please help me.

    ReplyDelete
    Replies
    1. hey harsha ,
      if you want to store these value use one array in in Main.java and store those value (Store position variable in it) and if user again go to list view pass those value to Listadapter class and over their write code for again check those check boxes.
      i hope you understand what i mean.

      Delete
  7. Hi - thanks for the tutorial. I have a problem. When listview is scrolled, the checkbox state gets unchecked. I debugged a little to find that "holder.ck1.setOnClickListener -> onClick" is never getting called. As a result "itemChecked[position] = true;" never happens. Do you have working files of this project you could probably provide? It would be immense help. My email is mavdev32@gmail.com

    ReplyDelete
    Replies
    1. hey penfriend
      check your mail i have sent you working files and one gif also that i have recorded just now for you.
      its working fine and i hope you will solve your problem. if not let me know ..

      Delete
  8. great post. would be helpful if u could add some comments in the code

    ReplyDelete
  9. Replies
    1. Download link is working you can download from there.
      Sorry I can not mail each and every one.

      Delete
  10. Great post thanks...
    i have one question how can we perform select all operation in the same code? thanks

    ReplyDelete
  11. Hello Wasim Memon,
    if i want to Select all Checkbox functionality from my fragment activity than how can i do?
    Please tell me .

    ReplyDelete
  12. Situation : How we can make two click listener if user want to open file it click on file if user want to delete file then it may check ....?? Like file browser

    ReplyDelete
    Replies
    1. Can you explain it more ?
      because i can't understand what do you mean by 2 click listener ?

      Delete
  13. I have add a check box for selectall checkbox to selct a selectAll check box only select 6 items from a list remaning are not selected to the view .Actually all check boxes are selected list items (I have loged to observe) but scroll down a listview items delselt the check boxes.

    ReplyDelete
  14. selectAll.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {
    try
    {
    int listCount =myValuesArr.size();
    if(listCount > 0)
    {

    for (int i = 0; i < listCount; i++)
    {
    View view = (View) listView.getChildAt(i);
    if(view !=null)
    check= (CheckBox)view.findViewById(R.id.selectRecord);
    if(selectAll.isChecked())
    {log.debug("checkd Item"+i);
    check.setChecked(true);
    }
    else
    {log.debug("uncheck Item"+i);
    check.setChecked(false);
    }

    }
    }
    else{
    Toast.makeText(getApplicationContext(), "No Records to Select", Toast.LENGTH_SHORT).show();
    }
    } catch (Exception e) {
    log.error( TFUtils.getErrorMessage(e));
    }
    }
    });

    to selct all checkboxes but scroll down on listview items deslect check boxes what is a problem please help me

    ReplyDelete
    Replies
    1. Hey Srihari,
      Ok i understood your issue but let me tell you something.
      listview.getChildAt(i) will return null for those view which are scrolled up or down. b'z list view recycle those view once it gets out of the screen. that's how listview works. so if you want that if selectallcheckbox is checked you have to set select new view when its get generate.

      i mean in getview when you return new view make sure it is preselected.
      <pre>
      @Override
      public View getView(int position, View convertView, ViewGroup parent)
      {
      ViewHolder holder;

      if (convertView == null)
      {
      holder = new ViewHolder();

      convertView = LayoutInflater.from(context).inflate(layoutResource,null);


      convertView.setTag(holder);
      }
      else
      {
      holder = (ViewHolder) convertView.getTag();
      }



      if (itemChecked[position])
      holder.ck1.setChecked(true);
      else
      holder.ck1.setChecked(false);

      holder.ck1.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {

      // TODO Auto-generated method stub
      if (holder.ck1.isChecked())
      itemChecked[position] = true;
      else
      itemChecked[position] = false;
      }
      });

      if(selectAllItemChecked)
      {
      holder.ck1.setChecked(true);
      }


      return convertView;
      }
      </pre>
      One more thing you have to maintain one flag between activity and adapter for select all because it is not part of listview.
      i hope it is clear to you.

      Delete
  15. Thanks for the amazing tutorial. I am stuck at a point that I've mentioned below:

    I am trying to run the above pasted code in Android Studio. On clicking the checkboxes and the "Check Selected" button, it shows "null" message through toast instead of the tv i.e textview1.

    Any ideas on this?

    ReplyDelete
    Replies
    1. Hi aka,
      Can you paste some code over here.
      So I can help. You can find source zip so you can download and find what's issue.

      Delete
    2. I have written the same code as you have taught here @Wasim but I am having the same issue as @Aka here. When I run the application, it runs fine, the problem is when I check some apps and then click the button then in toast null message is shown, and not the app names.

      Delete
    3. @Sophia Ajaz
      I have already provided link for code zip so you can download and compare with your code.
      I don't have your code and scenario so i can't help you.
      Thanks

      Delete
  16. Hi Wasim thanks for this code but it not showing some apps like Hangout,Chrom etc... plz guide get all apps ....

    ReplyDelete
    Replies
    1. @Abhishek Kumar
      Before creating list you have to check if it is system app or not. if not then only add into list and then display. it will remove all system and google preinstalled apps.

      Delete
  17. Thank for the code it's really help.

    Now I want to add selected listview to another activity when tick and remove when untick.
    Do you have any code for that?

    Thanks.

    ReplyDelete
  18. How to add the selected listview to another activity such as FavoriteActivity and delete when untick

    ReplyDelete
    Replies
    1. To pass selected values to another activity use list or arraylist and on button click pass that list to another activity or fragment.
      Hope it is what you are asking.

      Delete
  19. App is crashing at onItemClickListener but when I remove this part:
    if (cb.isChecked()) {

    checkedValue.add(tv.getText().toString());
    } else if (!cb.isChecked()) {
    checkedValue.remove(tv.getText().toString());
    }

    It works fine and performClick also works.
    So tell me what's the problem here Please

    ReplyDelete
    Replies
    1. Hey Aleem,
      I can't tell about error from this much code but check if you have initialized checkedValue array list or not.
      that might be null and you are trying to add/remove value so it can create problem.

      Delete
  20. Hi, This works perfectly fine. But when I click only on the checkbox, the "checkvalues" array is not filled. But if I touch on the text, the array gets filled. Any clue ?

    Thanks in advance.

    ReplyDelete
    Replies
    1. Hi archer,
      it is because of these attribute <pre> android:descendantFocusability="blocksDescendants" </pre>
      this attribute actually stops getting focus or touch to child views so when you touch it won't pass event to check box but when you click on list i have manually called check box check event and then array gets filled.

      I hope its clear to you now.

      Delete
  21. Hello sir,
    I want to select check box values and copy them into device folder.I also created a folder,but selected values are not stored,it takes all list.
    plz give me solution...Thanks in advanced

    ReplyDelete
  22. Hello sir..
    i want to select check box values and copy them into folder.i also create a folder but selected item not copied.all items are copied...

    ReplyDelete
    Replies
    1. I have already attached code zip file so download it and debug it. i hope you will find issue.

      Delete
  23. Hello Wasim, First, Thank you very much for this helpful code. Second, I'm just copy paste your code, it works fine but the toast msg always return null! any suggestions?

    ReplyDelete
    Replies
    1. I have already attached code zip file so download it and debug it. i hope you will find issue.

      Delete