Monday, September 2, 2013

Android Dynamic Check-box Example | Check-box Demo in Android | Manage click in dynamic check-box in android

Hello Friends!
Today I am sharing very important code for dynamic check-box in android. Main part of this demo is manage dynamic click of check-box. Just copy paste below code and modify according your need.


MainActivity.java


package com.manish.checkboxdemo;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;

import com.manish.checkboxdemo.R;

/**
 * 
 * @author manish
 * 
 */

public class MainActivity extends Activity {
 LinearLayout linearMain;
 CheckBox checkBox;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  linearMain = (LinearLayout) findViewById(R.id.linearMain);
  /**
   * create linked hash map for store item you can get value from database
   * or server also
   */
  LinkedHashMap<String, String> alphabet = new LinkedHashMap<String, String>();
  alphabet.put("1", "Apple");
  alphabet.put("2", "Boy");
  alphabet.put("3", "Cat");
  alphabet.put("4", "Dog");
  alphabet.put("5", "Eet");
  alphabet.put("6", "Fat");
  alphabet.put("7", "Goat");
  alphabet.put("8", "Hen");
  alphabet.put("9", "I am");
  alphabet.put("10", "Jug");

  Set<?> set = alphabet.entrySet();
  // Get an iterator
  Iterator<?> i = set.iterator();
  // Display elements
  while (i.hasNext()) {
   @SuppressWarnings("rawtypes")
   Map.Entry me = (Map.Entry) i.next();
   System.out.print(me.getKey() + ": ");
   System.out.println(me.getValue());

   checkBox = new CheckBox(this);
   checkBox.setId(Integer.parseInt(me.getKey().toString()));
   checkBox.setText(me.getValue().toString());
   checkBox.setOnClickListener(getOnClickDoSomething(checkBox));
   linearMain.addView(checkBox);
  }

 }

 View.OnClickListener getOnClickDoSomething(final Button button) {
  return new View.OnClickListener() {
   public void onClick(View v) {
    System.out.println("*************id******" + button.getId());
    System.out.println("and text***" + button.getText().toString());
   }
  };
 }

}

activity_main.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/linearMain"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

</LinearLayout>

AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.manish.checkboxdemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.manish.checkboxdemo.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Thanks!

25 comments:

  1. Hello sir, your tutorial is great. but i have one query that i have arraylist which i have populated into listview and one customadapter class where using getview method i set. i.e eachrow has one textview and checkbox. i want to do when checkbox is clicked or checked corresponding textview is removed.i.e list.remove(position) so, how can i get checkbox position into listview . thanks.

    ReplyDelete
    Replies
    1. Hi Viral,
      I think if you want remove any item on check then use delete button instead of checkbox. because checkbox use is perform task on selected items not for single item.Anyway its all your logic, do as your requirement.

      1)Add a delete button any where on your layout.
      2)set id for all of your checkbox.
      3)on delete button press get all selected id and remove that row from your list.
      4)if you are using webservice update your server with that deleted item and if local sqlite or any other collection framework just update that.
      5)refill your adapter on notifychange.

      you can check my this post-
      http://www.androidhub4you.com/2013/02/muftitouch-listview-multi-click.html

      Delete
  2. thanks a lot.. sir
    Hello sir, I have Arraylist into bean class@Line 1 Below. I have mainActivity class @ Line 2 Below where i set data to listview using myAdapter(CustomAdapter class). each row has one textview and checkbox. i want to do when checkbox is checked i want to obtain that checkbox position so i can remove corresponding textview so, i used below l1.remove(i) it' s work find but what happen i have to click on listview item to remove the item but want to remove when checkbox is checked or clicked i want to remove corresponding item. thanks.


    Line 1>>> public class Bean {




    static ArrayList getList(){

    ArrayList l1=new ArrayList();

    l1.add("Laptop");
    l1.add("Desktop");
    l1.add("Pendrive");

    return l1;
    }
    }
    //////////////////////////////////////////////



    Line 2>> public class MainActivity extends Activity {

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


    final ArrayList l1=Bean.getList();



    final ListView l2=(ListView)findViewById(R.id.listView1);
    Button b1=(Button)findViewById(R.id.button1);


    final myAdapter1 adapter = new myAdapter1(this, l1);
    l2.setAdapter(adapter);




    b1.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
    // TODO Auto-generated method stub

    SparseBooleanArray boolArray=l2.getCheckedItemPositions();

    for(int i=0;i> public class myAdapter1 extends BaseAdapter
    {



    ArrayList listItem;

    Activity activity;




    public myAdapter1(Activity activity, ArrayList l1) {
    // TODO Auto-generated constructor stub
    listItem=l1;
    this.activity=activity;
    }

    @Override
    public int getCount() {
    // TODO Auto-generated method stub
    return listItem.size();
    }

    @Override
    public Object getItem(int position) {
    // TODO Auto-generated method stub
    return null;
    }

    @Override
    public long getItemId(int position) {
    // TODO Auto-generated method stub
    return 0;
    }

    public class ViewHolder
    {
    TextView txtViewItem;
    CheckBox chk;
    }

    @Override
    public View getView(final int position, View view, ViewGroup parent) {
    // TODO Auto-generated method stub

    final ViewHolder item;
    LayoutInflater inflater = activity.getLayoutInflater();

    if(view==null)
    {
    view = inflater.inflate(R.layout.activity_main, null);
    item = new ViewHolder();

    item.txtViewItem = (TextView) view.findViewById(R.id.textView1);
    item.chk=(CheckBox)view.findViewById(R.id.checkBox1);
    view.setTag(item);
    }
    else
    {
    item = (ViewHolder) view.getTag();
    }

    item.txtViewItem.setText(listItem.get(position));



    return view;
    }
    }

    ReplyDelete
  3. Hmmm so very ease just remove arrayList item on check-box clicked. and for getting that potion you can get easily using my multi click demo..
    In your adapter get position and that delete that item from list and update your UI again.

    Thanks!

    ReplyDelete
  4. Thanks a lot sir..i will follow ur guidelines.

    ReplyDelete
  5. plz, check following code ....

    Query 1>
    When i checked only one checkbox and press button it's removed corresponding textview but when i unchecked it it also removed corresponding textview.
    Query 2>
    When i checked first item into list and third item into list it's give me exception java.lang.IndexOutOfBoundsException: Invalid index 2, size is 2 it's only checked one item at a time. so, how can i achieve when unchecked checkbox is not removed corresponding textview and also multiple item i checked can remove item when button is pressed.. following is my code what's wrong with in that..thanks.

    public class MainActivity extends Activity {


    Bean b2=new Bean();

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


    final ArrayList l1=Bean.getList();



    final ListView l2=(ListView)findViewById(R.id.listView1);
    Button b1=(Button)findViewById(R.id.button1);


    final myAdapter1 adapter = new myAdapter1(this, l1);
    l2.setAdapter(adapter);




    b1.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
    // TODO Auto-generated method stub

    //SparseBooleanArray boolArray=l2.getCheckedItemPositions();


    adapter.notifyDataSetChanged();



    }
    });



    }


    }


    public class myAdapter1 extends BaseAdapter
    {



    ArrayList listItem;

    Activity activity;




    public myAdapter1(Activity activity, ArrayList l1) {
    // TODO Auto-generated constructor stub
    listItem=l1;
    this.activity=activity;
    }


    @Override
    public int getCount() {
    // TODO Auto-generated method stub
    return listItem.size();
    }

    @Override
    public Object getItem(int position) {
    // TODO Auto-generated method stub
    return null;
    }

    @Override
    public long getItemId(int position) {
    // TODO Auto-generated method stub
    return 0;
    }

    public class ViewHolder
    {
    TextView txtViewItem;
    CheckBox chk;
    }

    @Override
    public View getView(final int position, View view, ViewGroup parent) {
    // TODO Auto-generated method stub

    final ViewHolder item;
    LayoutInflater inflater = activity.getLayoutInflater();

    if(view==null)
    {
    view = inflater.inflate(R.layout.activity_main, null);
    item = new ViewHolder();

    item.txtViewItem = (TextView) view.findViewById(R.id.textView1);
    item.chk=(CheckBox)view.findViewById(R.id.checkBox1);
    view.setTag(item);
    }
    else
    {
    item = (ViewHolder) view.getTag();
    }

    item.txtViewItem.setText(listItem.get(position));

    item.chk.setOnCheckedChangeListener(new OnCheckedChangeListener() {

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    // TODO Auto-generated method stub


    if(item.chk.isChecked()){

    listItem.remove(position);
    }


    }

    });

    return view;
    }
    }

    ReplyDelete
  6. hello sir, have u checked my previous post what i have to do to achieve that ..thanks.

    ReplyDelete
  7. ok sir, thanks.you are great for trainee.

    ReplyDelete
    Replies
    1. Thanks Viral, and i am not great, just want share knowledge with others. Actually i am some busy now in these days so i did not see your code. But no worry I will give you demo code when i got free. Till then try at your end if you got any luck let me know. Otherwise till then you can work on others module.

      Thanks!

      Delete
  8. Can someone please give me any suggestions to resolve this problem on SO
    http://stackoverflow.com/questions/21091429/failed-to-print-position-of-clickeditem-of-listview-in-android-using-java/21091513?noredirect=1#comment31725907_21091513

    ReplyDelete
  9. Hi Manish,
    Its a great one. Please let me know how to save check box data in database if there are multiple check boxes like []java []c []linux if i select java and android both how to store them in database and retrieve from database. I am beginner please help me

    ReplyDelete
  10. Hi Manish,

    how to save this check box value in same activity

    ReplyDelete
  11. Hi Manish,
    Its a great one. Please let me know how to save check box data in database if there are multiple check boxes values how to store them in database and retrieve from database. I am beginner please help me


    ReplyDelete
  12. Hi anyone tell me how to uncheck checbox on a listview when one check box is Checked. If you are good android DEVELOPER answer me,else YOU are .....(fill yourself)

    ReplyDelete
    Replies
    1. Why should we answer? You are not a good developer? you can't do it by yourself? Are you paying to us? we are here for helping people who really need help not like you claiming challenges. This is a free web site and I am owner of this web site, if you find anything helpful from here that's good and if not go and find some where else but think ones if someone help you in your code means he is consuming his/her time from their schedule and someone writing blog or answering on stack-overflow you must respect to him/her. If no one share their knowledge you will struggle. Hope you can understand now. Best of luck and your comment is not an issue for me i can delete in a minute but i don't care what you are writing and why.

      And still you have any doubt let us do have a deal pay $250 for my time I will give your solution. And if not I will pay you $500.

      Delete
  13. This comment has been removed by the author.

    ReplyDelete
  14. Hi, Manish! I want to know how to get id of dynamically created checkbox. Currently, I can get only last created checkbox id....please help



    Read more: http://www.androidhub4you.com/2013/09/android-dynamic-check-box-example-check.html#ixzz3h4VVuPHr

    ReplyDelete
    Replies
    1. Please check here-

      View.OnClickListener getOnClickDoSomething(final Button button) {
      return new View.OnClickListener() {
      public void onClick(View v) {
      System.out.println("*************id******" + button.getId());
      System.out.println("and text***" + button.getText().toString());
      }
      };
      }


      OnCheckBox selected you will get a ID in logcat. It is not last one.

      Delete
    2. This comment has been removed by the author.

      Delete
  15. how to download your example ????

    ReplyDelete
  16. i have one example requirement...

    Is This....... recyclerview with checkbox complete example..

    any proper site??

    ReplyDelete
  17. Hello Sir,whenever I go out of an activity,dynamic checkbox disappears.How can I make that dynamic checkbox permenant whenever that activity is in start or resume or resatrt state?

    ReplyDelete
  18. Hello Sir,whenever I go out of an activity,dynamic checkbox disappears.How can I make that dynamic checkbox permenant whenever that activity is in start or resume or resatrt state?

    ReplyDelete
  19. can any one help how to store selected checkbox values

    ReplyDelete