1

What i have done::I have got s list of items from server & display in listview each row of list has a checkbox in it, list view also has a button on top as show in figure below


enter image description here


What i need to do ::

  1. out of six rows if i select three rows using checkbox on click of button next showed in figure i must be able to display the toast message of selected elements
  2. I don't know how to fill the parts of onclick function of checkButtonClick() in code

ListViewAdapterForAtomicListItemtype.java

public class ListViewAdapterForAtomicListItemtype extends BaseAdapter {

    // Declare Variables
    Context context;
    LayoutInflater inflater;
    ArrayList<HashMap<String, String>> data;
    HashMap<String, String> resultp = new HashMap<String, String>();

    public ListViewAdapterForAtomicListItemtype(Context context,
            ArrayList<HashMap<String, String>> arraylist) {
        this.context = context;
        data = arraylist;
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

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

    public View getView(final int position, View convertView, ViewGroup parent) {
        // Declare Variables
        TextView name;

        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View itemView = inflater.inflate(R.layout.listview_item_for_atomic_list_item_type, parent, false);
        // Get the position
        resultp = data.get(position);

        // Locate the TextViews in listview_item.xml
        name = (TextView) itemView.findViewById(R.id.textView_id_atomic_list_item_type);

        // Capture position and set results to the TextViews
        name.setText(resultp.get(MainActivity.NAME));


        return itemView;
    }
}

listview_main_atomic_list_itemtype.xml

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

    <ListView
        android:id="@+id/listview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_below="@+id/button1" />

    <Button
        android:id="@+id/button_of_listview_main_atomic_list_itemtype_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:text="DisplayItems" />

</RelativeLayout>

listview_item_for_atomic_list_item_type.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/textView_id_atomic_list_item_type"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="17dp"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <CheckBox
        android:id="@+id/checkBox_atomic_list_item_type_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true" />

</RelativeLayout>

BLD_IndividualListOfItems_Starters.java

public class BLD_IndividualListOfItems_Starters extends Activity{
    // Declare Variables
    JSONObject jsonobject;
    JSONArray jsonarray;
    ListView listview;
    ListViewAdapterForAtomicListItemtype adapter;
    ProgressDialog mProgressDialog;
    ArrayList<HashMap<String, String>> arraylist;
    static String NAME = "rank";


    String TYPE_FILTER;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Get the view from listview_main.xml
        setContentView(R.layout.listview_main_atomic_list_itemtype);

        TYPE_FILTER = getIntent().getExtras().getString("key_title");
        Log.v("---- Value-Start---", TYPE_FILTER);
        // Locate the listview in listview_main.xml
        listview = (ListView) findViewById(R.id.listview);

        // Execute DownloadJSON AsyncTask
        new DownloadJSON().execute();
    }

    // DownloadJSON AsyncTask
    private class DownloadJSON extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Create a progressdialog
            mProgressDialog = new ProgressDialog(BLD_IndividualListOfItems_Starters.this);
            // Set progressdialog title
            //mProgressDialog.setTitle("Fetching the information");
            // Set progressdialog message
            mProgressDialog.setMessage("Loading...");
            mProgressDialog.setIndeterminate(false);
            // Show progressdialog
            mProgressDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            // Create an array
            arraylist = new ArrayList<HashMap<String, String>>();

            String newurl = "?" + "Key=" + TYPE_FILTER;


            // Retrieve JSON Objects from the given URL address
            jsonobject = JSONfunctions.getJSONfromURL("http://54.218.73.244:7005/RestaurantAtomicListItemType/"+newurl);

            try {
                // Locate the array name in JSON
                jsonarray = jsonobject.getJSONArray("restaurants");

                for (int i = 0; i < jsonarray.length(); i++) {
                    HashMap<String, String> map = new HashMap<String, String>();
                    jsonobject = jsonarray.getJSONObject(i);
                    // Retrive JSON Objects
                    map.put(MainActivity.NAME, jsonobject.getString("MasterListMenuName"));

                    // Set the JSON Objects into the array
                    arraylist.add(map);
                }
            } catch (JSONException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void args) {
            // Pass the results into ListViewAdapter.java
            adapter = new ListViewAdapterForAtomicListItemtype(BLD_IndividualListOfItems_Starters.this, arraylist);
            // Set the adapter to the ListView
            listview.setAdapter(adapter);
            // Close the progressdialog
            mProgressDialog.dismiss();
        }
    }



    private void checkButtonClick() {


        Button myButton = (Button) findViewById(R.id.button_of_listview_main_atomic_list_itemtype_id);
        myButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {





            }
        });

    }
}

{EDIT}

BLD_IndividualListOfItems_Starters.java

public class BLD_IndividualListOfItems_Starters extends Activity{
    // Declare Variables
    JSONObject jsonobject;
    JSONArray jsonarray;
    ListView listview;
    ListViewAdapterForAtomicListItemtype adapter;
    ProgressDialog mProgressDialog;
    ArrayList<HashMap<String, String>> arraylist;
    static String NAME = "rank";


    String TYPE_FILTER;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Get the view from listview_main.xml
        setContentView(R.layout.listview_main_atomic_list_itemtype);

        TYPE_FILTER = getIntent().getExtras().getString("key_title");
        Log.v("---- Value-Start---", TYPE_FILTER);
        // Locate the listview in listview_main.xml
        listview = (ListView) findViewById(R.id.listview);

        // Execute DownloadJSON AsyncTask
        new DownloadJSON().execute();
    }

    // DownloadJSON AsyncTask
    private class DownloadJSON extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Create a progressdialog
            mProgressDialog = new ProgressDialog(BLD_IndividualListOfItems_Starters.this);
            // Set progressdialog title
            //mProgressDialog.setTitle("Fetching the information");
            // Set progressdialog message
            mProgressDialog.setMessage("Loading...");
            mProgressDialog.setIndeterminate(false);
            // Show progressdialog
            mProgressDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            // Create an array
            arraylist = new ArrayList<HashMap<String, String>>();

            String newurl = "?" + "Key=" + TYPE_FILTER;


            // Retrieve JSON Objects from the given URL address
            jsonobject = JSONfunctions.getJSONfromURL("http://54.218.73.244:7005/RestaurantAtomicListItemType/"+newurl);

            try {
                // Locate the array name in JSON
                jsonarray = jsonobject.getJSONArray("restaurants");

                for (int i = 0; i < jsonarray.length(); i++) {
                    HashMap<String, String> map = new HashMap<String, String>();
                    jsonobject = jsonarray.getJSONObject(i);
                    // Retrive JSON Objects
                    map.put(MainActivity.NAME, jsonobject.getString("MasterListMenuName"));

                    // Set the JSON Objects into the array
                    arraylist.add(map);
                }
            } catch (JSONException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void args) {
            // Pass the results into ListViewAdapter.java
            adapter = new ListViewAdapterForAtomicListItemtype(BLD_IndividualListOfItems_Starters.this, arraylist);
            // Set the adapter to the ListView
            listview.setAdapter(adapter);
            // Close the progressdialog
            mProgressDialog.dismiss();
        }
    }



    private void checkButtonClick() {


        Button myButton = (Button) findViewById(R.id.button_of_listview_main_atomic_list_itemtype_id);
        myButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {


                StringBuilder result = new StringBuilder();
                   for(int i=0;i<arraylist.size();i++)
                   {
                          if(adapter.mCheckStates.get(i)==true)
                          {

                              result.append(arraylist.get(i).get(MainActivity.NAME));
                              result.append("\n");
                          }

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


            }
        });

    }
}

ListViewAdapterForAtomicListItemtype.java

public class ListViewAdapterForAtomicListItemtype extends BaseAdapter implements android.widget.CompoundButton.OnCheckedChangeListener{

    // Declare Variables
    Context context;
    LayoutInflater inflater;
    ArrayList<HashMap<String, String>> data;
    HashMap<String, String> resultp = new HashMap<String, String>();

    SparseBooleanArray mCheckStates; 

    public ListViewAdapterForAtomicListItemtype(Context context,
            ArrayList<HashMap<String, String>> arraylist) {
        this.context = context;
        data = arraylist;
        mCheckStates = new SparseBooleanArray(data.size()); 
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

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

    public View getView(final int position, View convertView, ViewGroup parent) {
        // Declare Variables
        TextView name;



        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View itemView = inflater.inflate(R.layout.listview_item_for_atomic_list_item_type, parent, false);
        // Get the position

        CheckBox chkSelect =(CheckBox) itemView.findViewById(R.id.checkBox_atomic_list_item_type_id);

        chkSelect.setTag(position);
        chkSelect.setChecked(mCheckStates.get(position, false));
        chkSelect.setOnCheckedChangeListener(this);


        resultp = data.get(position);

        // Locate the TextViews in listview_item.xml
        name = (TextView) itemView.findViewById(R.id.textView_id_atomic_list_item_type);

        // Capture position and set results to the TextViews
        name.setText(resultp.get(MainActivity.NAME));


        return itemView;
    }

    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);    

    }
}
smriti3
  • 871
  • 2
  • 15
  • 35
  • check this http://stackoverflow.com/questions/18162931/android-get-selected-item-using-checkbox-in-listview-when-i-click-a-button – Raghunandan Dec 31 '13 at 10:13
  • you need to understand the code posted in the link first. Then you can ask what is confusing for you. I can give you a code but what good that would be as you would not understadn – Raghunandan Dec 31 '13 at 10:29
  • i did this task simply using ArrayAdapter by manually adding elements .... but when base adapter is there im confused – smriti3 Dec 31 '13 at 10:32
  • which part is confusing?? – Raghunandan Dec 31 '13 at 10:33

4 Answers4

1

you can also use for MULTIPLE CHOICE OF LISTVIEW.

StringBuilder result;

After Click on Button you can do this:

btn.setOnClickListener(new OnClickListener() {

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

            result = new StringBuilder();
            for (int i = 0; i < arraylist.size(); i++) {
                if (adapter.mysparse.get(i) == true) {

                    result.append(arraylist.get(i).get(MainActivity.NAME));
                    result.append("\n");
                }

            }
            Intent n = new Intent(MainActivity.this, DisplayActivity.class);
            n.putExtra("buffer", result.toString());
            startActivity(n);
        }
    });

And in your DisplayActivity you can do like this:

package com.example.singleitemlistview;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class DisplayActivity extends Activity {

ListView lv;
ArrayList<String> myList;
String myName;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.second);

    Intent n = getIntent();
    myName = n.getStringExtra("buffer");

    myList = new ArrayList<String>();

    lv = (ListView) findViewById(R.id.listViewData);

    myList.add(myName);

    lv.setAdapter(new ArrayAdapter<String>(DisplayActivity.this,
            android.R.layout.simple_list_item_1, myList));

}

}

Piyush
  • 18,895
  • 5
  • 32
  • 63
1

Use a SparseBooleanArray.

More info @

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

In your adapter implement CompoundButton.OnCheckedChangeListener

public class ListViewAdapterForAtomicListItemtype extends BaseAdapter implements CompoundButton.OnCheckedChangeListener
{
SparseBooleanArray mCheckStates; 

 public ListViewAdapterForAtomicListItemtype(Context context,
            ArrayList<HashMap<String, String>> arraylist) {
        this.context = context;
        data = arraylist;
         mCheckStates = new SparseBooleanArray(data.size()); 
    }

Then in getView

   CheckBox chkSelect =(CheckBox) item.findViewById(R.id.CheckBox
    android:id="@+id/checkBox_atomic_list_item_type_id");

   chkSelect.setTag(position);
   chkSelect.setChecked(mCheckStates.get(position, false));
   chkSelect.setOnCheckedChangeListener(this);

Override the following methods

    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);    

}

In onClick of Button

   StringBuilder result = new StringBuilder();
   for(int i=0;i<arraylist.size();i++)
   {
          if(adapter.mCheckStates.get(i)==true)
          {

              result.append(arrayList.get(i).get(MainActivtiy.Name));
              result.append("\n");
          }

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

Note:

It is better to use a ViewHolder Pattern.

http://developer.android.com/training/improving-layouts/smooth-scrolling.html

Raghunandan
  • 132,755
  • 26
  • 225
  • 256
  • what is compound ...is it interface ? u have not mentioned in answer – smriti3 Dec 31 '13 at 11:05
  • @smriti3 yes it an interface. I have mentioned pls take a look at the code again. see the keyword implements?? – Raghunandan Dec 31 '13 at 11:32
  • @ Raghunandan .... I might not be right ... but ... as i see u have implemented it but where have u defined it ? – smriti3 Dec 31 '13 at 11:37
  • @smriti3 you are all wrong. check this http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/1.6_r2/android/widget/CompoundButton.java. Do oyu have the right import. Its the interface from the android source code not the one i defined – Raghunandan Dec 31 '13 at 11:40
  • @ Raghunandan ... I found why i was not able to implement compound ... have a look at here http://stackoverflow.com/a/19842093/2901850 .... Still my Toast message is not displayed .... please have a look at edit – smriti3 Jan 01 '14 at 04:56
  • @smriti3 i have given you a solution. you should be able to implement it. You have a checkbox or RadioGroup – Raghunandan Jan 01 '14 at 05:28
0
StringBuffer result = new StringBuffer();
        result.append("TEXTVIEW 1  : ").append(chkbox1.isChecked());
        result.append("\nTEXTVIEW 2 : ").append(chkbox2.isChecked());
        result.append("\nTEXTVIEW 3 :").append(chkbox3.isChecked());

                //and so on.........

        Toast.makeText(MyAndroidAppActivity.this, result.toString(),
                Toast.LENGTH_LONG).show();

I think this wat you need. Just update you got solution or not. this code must be in the next button onclickListener. Try it out nd vote and ping if works. before tat update wats happening.

ADDED:

mainListView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {

                String ss;
                ss=(String) ((TextView) view).getText();

This code is to check which item is clicked. by this with lenght of the list , check in for loop to check whether its checkbox is clicked or not.

Aftert that you can easily append that list of checked items.

kathir
  • 489
  • 2
  • 11
  • how do you know there are 3 checkboxes or more and how do oyu get references to checkbox1 and 2 and so on... also op is using a custom adapter – Raghunandan Dec 31 '13 at 10:22
  • Its sample only to underdstand. As for your question you need to get the value of textview of the list item which are all checked. Then after that you need to append the values to string as above for the checked list. – kathir Dec 31 '13 at 10:27
  • i understand its a sample but i don't understand how you get reference to checkbox1,2 and so on – Raghunandan Dec 31 '13 at 10:28
  • i added something to my above answers , check it out. – kathir Dec 31 '13 at 10:34
0

Never tried but should work..you can use following code inside onClick() to get CheckBox status for each row.

    if (adapter!=null&&adapter.getCount()>0) {
        for(int i=0;i<adapter.getCount();i++){
            View view=(View)adapter.getItem(i);
            CheckBox chk=(CheckBox)view.findViewById(R.id.checkbox);
            TextView txt=(TextView)view.findViewById(R.id.textview);
            if (chk.isChecked()) {
                //do something here
            }
        }
    }
Ketan Ahir
  • 6,678
  • 1
  • 23
  • 45