Question

How to get the selected position in checkbox itemId.

I have two item Veg and non-veg item. I want the result for veg Items only. I show the screen in veg items .But it is not working for veg list checked items.

Response

|1|Amaretto cookies|True
  1. is itemId

  2. food item

  3. True/False.

Based on True or False I need to check the check boxes and retrieve the checked items

Veg items:

|21|1|Amaretto cookies|True|2|Amish White Bread|True|6|Caesar Salad|True|10|Guacamole|True|13|Macaroni and Cheese|True|16|Pancakes|True|17|Pasta|True|18|Ribollita|True|20|Pizza|True|21|Seven Layer Taco Dip|True|22|Shrimp Bisque|True|23|Spicy Bean Salsa|True|24|Sopapilla Cheesecake|True|25|Sopapilla Cheesecake Pie|True|26|Vegetarian Tortilla Stew|True|561|food|True|563|asdf|True|574|veg|True|579|a|True|593|hjg|True|619|hhy|True|

Non- Veg items:

|12|3|Barbeque|False|4|Buffalo Chicken Wings|False|5|Burgers|False|7|Classic Lasagna|False|8|Chicken Chow Mein|False|9|Fried Chicken|False|11|Japanese sushi|False|12|Mezze|False|14|Mutton Pepper Gravy|False|15|Paella Valenciana|False|19|Phad Thai Recipe|False|578|Pizza|False|

Url:

  String user_url="http://mobileapps.iwedplanner.com/mobileapps/iwedplanner/mobile/version21/mmealitems.aspx?uname="+LoginForm.str1+"&occasion="+occasionval;

Code:

    httpclass obj = new httpclass();
    result = obj.server_conn(user_url);
    System.out.println(result);
    if (result != null) 
    {           
        token = new StringTokenizer2(result, "");
    }
        value = new ArrayList<String>();

        while (token.hasMoreTokens()) 
        {
            value.add(token.nextToken());
        }   

        value.add(Integer.toString(value.size()));

        Integer k=null; 
        table=new Hashtable<Integer,ArrayList<String>>();
        itemId = new ArrayList<String>();   
        stritem = new ArrayList<String>();
        vegitems = new ArrayList<String>();
        nonvegitems = new ArrayList<String>();

        int id=0,c=0,n=value.size();

        for(int j=0; j<n; j++)
        {               
             z = value.get(j);

        String[] mystring  = z.split("<br>");

            int arraysize = mystring.length;

            for(int a=0; a<arraysize-1;a++)
            {

                str2.add(mystring[0]);

                str3.add(mystring[1]);
            }

        }

        for(int g=0; g<str2.size();g++)
        {               
            String name = str2.get(g);

            token2 = new StringTokenizer2(name, "|", false);

            while (token2.hasMoreTokens()) 
            {
            vegitems.add(token2.nextToken());
            }

        }

        for(int x=1;x<vegitems.size();x++)
        {   
            itemId.add(vegitems.get(x));
            x=x+1;

            stritem.add(vegitems.get(x));
            x=x+1;

            status.add(vegitems.get(x));

        }                           
        setListAdapter(new IconicAdapter(this));
        selection = (TextView) findViewById(R.id.selection);

        getListView().setTextFilterEnabled(true);

        save.setOnClickListener(new OnClickListener() 
        { 
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                tru = new StringBuffer();
                fals = new StringBuffer();

                for (int i = 0; i<status.size();i++) 
                {
                    if (status.get(i).equals("True"))

                        tru.append(itemId.get(i)+",");
                    else
                        fals.append(itemId.get(i)+",");
                }

                boolean netvalue = false;
                 ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);


                    NetworkInfo info = cm.getActiveNetworkInfo();
                    if (info != null && info.isAvailable()) {
                                            String user_url="http://mobileapps.iwedplanner.com/mobileapps/iwedplanner/mobile/version21/minsertmealchoiceNew.aspx?uname="+username+"&occasion="+occasionval+
                            "&choice="+tru+fals+"&ownchoice=&category=";

                    httpclass obj = new httpclass();
                    result = obj.server_conn(user_url);

                    StringTokenizer st = new StringTokenizer(result, "|");
                    result = st.nextToken();

                    if ((result.equals("Engagement 1&")) || (result.equals("Wedding 1&")) || (result.equals("Reception 1&"))) 
                    {


@SuppressWarnings("rawtypes")
class IconicAdapter extends ArrayAdapter 
{
    Activity context;

    @SuppressWarnings("unchecked")
    IconicAdapter(Activity context)                    
    {
        super(context, R.layout.rsvp_mealsse, stritem);

        this.context = context;
    }

@Override

public View getView(int position, View convertView, ViewGroup parent) 
{
        LayoutInflater inflater = context.getLayoutInflater();
        View row = inflater.inflate(R.layout.rsvp_mealsse,null);//viewappointlist, null);

        TextView index = (TextView) row.findViewById(R.id.index);
        index.setText(String.valueOf(position+1)+".");


        TextView label = (TextView) row.findViewById(R.id.title);
        label.setText(stritem.get(position));


        CheckBox check=(CheckBox)row.findViewById(R.id.check);

        check.setId(Integer.parseInt(itemId.get(position)));


        if(status.get(position).equals("True"))
             check.setChecked(true);


            else
             check.setChecked(false);


                check.setOnCheckedChangeListener(new OnCheckedChangeListener()
                {

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

                        int ind=itemId.indexOf(String.valueOf(buttonView.getId()));
                        status.set(ind, String.valueOf(isChecked));

                    }

                });


        return (row);

}
}

Snap :

This is what it should look like.False items are checked in the snap

enter image description here

Above shows the full code of my project.

These are my requirements:

It is all about event planner for Food. The invited guests can select and save the interested food items such as pizza, Caesar salad, Ameretocokies etc from the items list and mail to the inviter so that the inviter can view the saved items and arrange for the selected items.

Was it helpful?

Solution

I picked the solution from Romain Guy's solution @

https://groups.google.com/forum/?fromgroups#!topic/android-developers/No0LrgJ6q2M

I have used a ViewHolder pattern for smooth scrolling and performance. I have used a SparseBooleanArray to get checked items.

I assume you want the items whose corresponding check boxes are checked.

Also check this to understand listview re-cycles views

How ListView's recycling mechanism works

public class dsds extends Activity
{

    ListView lv;
    String result = null;
    StringTokenizer2 token = null,token2=null;;

    ArrayList<String> value,value2 = null; 
    ArrayList<String> str = null;
    ArrayList<String> str2 = null;
    ArrayList<String> newstatus=null;
    Hashtable<Integer, String> checkstatus=null;
    ArrayList<String>stateId=null;
    StringBuffer tru,fals;
    private SparseBooleanArray mCheckStates;
    String z;
    ArrayList<Holder> ha = new ArrayList<Holder>();
    @Override
    public void onCreate(Bundle savedInstanceState)
     {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.text);
         str2 = new ArrayList<String>();        
         stateId = new ArrayList<String>(); 
         newstatus=new ArrayList<String>();
         lv = (ListView) findViewById(R.id.listView1);
           Button b= (Button) findViewById(R.id.button1);
           new TheTask().execute();
            b.setOnClickListener(new OnClickListener()
            {

                @Override
                public void onClick(View v) {
                    StringBuilder result = new StringBuilder();
                    for(int i=0;i<str2.size();i++)
                    {
                        if(mCheckStates.get(i)==true)
                        {
                            result.append(str2.get(i));
                            result.append("\n");
                        }

                }
                Toast.makeText(dsds.this, result, 1000).show();
                }

            });
     }   
    class TheTask extends AsyncTask<Void,Void,Void>
    {

        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub
            HttpClient httpclient = new DefaultHttpClient();
            httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
            HttpGet request = new HttpGet("http://mobileapps.iwedplanner.com/mobileapps/iwedplanner/mobile/version21/mmealitems.aspx?uname=abcdefg&occasion=Engagement");

            try
            {
            HttpResponse response = httpclient.execute(request);
            HttpEntity resEntity = response.getEntity();
            String _response=EntityUtils.toString(resEntity);

                if (_response != null) 
                {
                    //alertbox("",result);
                     String[] mystring  = _response.split("<br>"); // splt by break
                     token = new StringTokenizer2(mystring[0], "|", false);// split by |
                     token2 = new StringTokenizer2(mystring[1], "|", false);
                }
             ///////    for veg
                    value = new ArrayList<String>();
                    while (token.hasMoreTokens()) 
                    {
                        value.add(token.nextToken());

                    }


                    for(int i=1;i<value.size()-1;i=i+3)
                    {

                   //   Log.i("....Veg ids.......",""+value.get(i));
                        stateId.add(value.get(i));
                    }
                    for(int i=2;i<value.size()-1;i=i+3)
                    {
                        str2.add(value.get(i));
                  //    Log.i("....Veg ids.......",""+value.get(i));
                    }
                    for(int i=3;i<=value.size()-1;i=i+3)
                    {
                        newstatus.add(value.get(i));
                //      Log.i("....Veg ids.......",""+value.get(i));
                    }
                // add all to list of Holder

                  for(int h=0;h<str2.size();h++)
                  {
                    Holder holder = new Holder();
                    holder.setTitle(str2.get(h));
                    holder.setId(stateId.get(h));
                    if(newstatus.get(h).equals("False"))
                    {
                        holder.setCheck(true);
                    }
                    else
                    {
                        holder.setCheck(false);
                    }
                    ha.add(holder);
                  }


            }catch(Exception e)
            {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            lv.setAdapter(new IconicAdapter(dsds.this));
        }

    }
    @SuppressWarnings("rawtypes")
    class IconicAdapter extends ArrayAdapter implements CompoundButton.OnCheckedChangeListener
    {
        Activity context;
        LayoutInflater mInflater;
        @SuppressWarnings("unchecked")
        IconicAdapter(Activity context)                    
        {
            super(context, R.layout.list_item, str2);
            mCheckStates = new SparseBooleanArray(str2.size());
            mInflater = LayoutInflater.from(context);
        }

    @Override

    public View getView(int position, View convertView, ViewGroup parent) 
    {
       ViewHolder holder;
       if(convertView==null)
       {
           convertView=mInflater.inflate(R.layout.list_item,parent,false);
           holder = new ViewHolder();
           holder.tv1 = (TextView) convertView.findViewById(R.id.textView1);
           holder.tv2 = (TextView) convertView.findViewById(R.id.textView2);
           holder.cb = (CheckBox) convertView.findViewById(R.id.checkBox1);
           convertView.setTag(holder);
       }
       else
       {
           holder = (ViewHolder) convertView.getTag();
       }
          Holder hol = ha.get(position);
          holder.tv1.setText(hol.getId().toString());
          holder.tv2.setText(hol.getTitle().toString());
          if(hol.isCheck()==true)
          {
          holder.cb.setChecked(mCheckStates.get(position, true));
          holder.cb.setTag(position);

          }
          else
          {
          holder.cb.setChecked(mCheckStates.get(position, false));
          holder.cb.setTag(position);

          }
          holder.cb.setOnCheckedChangeListener(this);
        return convertView;

    }

     public boolean isChecked(int position) {
         return mCheckStates.get(position, false);
     }

     public void setChecked(int position, boolean isChecked) {
         mCheckStates.put(position, isChecked);

     }

     public void toggle(int position) {
         setChecked(position, !isChecked(position));

     }
    @Override
    public void onCheckedChanged(CompoundButton buttonView,
            boolean isChecked) {

         mCheckStates.put((Integer) buttonView.getTag(), isChecked);    
    }

}
    static class ViewHolder
    {
        TextView tv1,tv2;
        CheckBox cb;
    }
}

Holder class

public class Holder {

    String title;
    String id;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    boolean check;
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public boolean isCheck() {
        return check;
    }
    public void setCheck(boolean check) {
        this.check = check;
    }

}

text.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" >

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

        <ListView
            android:id="@+id/listView1"
            android:layout_above="@id/button1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true" >

        </ListView>

    </RelativeLayout>

list_tiem.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" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="33dp"
        android:layout_marginTop="40dp"
        android:text="TextView" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/textView1"
        android:layout_centerHorizontal="true"
        android:text="TextView" />

    <CheckBox
        android:id="@+id/checkBox1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/textView2"
        android:layout_alignBottom="@+id/textView2"
        android:layout_alignParentRight="true"
        android:text="CheckBox" />

</RelativeLayout>

Snap

Now 1 and 2 are checked and when you click the button at the bottom you see the selected text. I checked 1 and 2 manually. However it depends on the response ie True or False. Right now all veg items are true.

Note: The list displays only veg items

enter image description here

OTHER TIPS

If you are using list-view and you want to check list-view item then you can use below code.

int len = mListView.getCount();
SparseBooleanArray checked = mListView.getCheckedItemPositions();
for (int i = 0; i < len; i++)
if (checked.get(i)){
..... // Your code whatever you want to do with selected item..
}
else{
.... 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top