Richa Singh
Richa Singh

Reputation: 603

How to get value from listview checkbox?

I am having a little trouble with listview, I want to get values of listview whose checkbox are selected when button is clicked. till now i have created a listview with checkboxes and fetched all the values from mysql but i am not able to get values of listview which are checked.

This is my class

public class ListViewMultipleSelectionActivity extends Activity{
    Button button;
    String myJSON;

    private static final String TAG_NAME = "cat_name";

    JSONArray peoples = null;

    ArrayList<HashMap<String, String>> personList;

    ListView list1;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        personList = new ArrayList<HashMap<String,String>>();
        list1 = (ListView) findViewById(R.id.list);
        button = (Button)findViewById(R.id.testbutton);
        getlat();



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


            }
        });

    }

    public void getlat(){
        class GetDataJSON extends AsyncTask<String, Void, String> {
            public void onPreExecute() {
            }
            @Override
            protected String doInBackground(String... params) {

                InputStream inputStream = null;
                String result = null;
                try {

                    URL url = new URL("http://xxxxxxxxxxxx/category.php");

                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setReadTimeout(15000 /* milliseconds */);
                    conn.setConnectTimeout(15000 /* milliseconds */);
                    conn.setRequestMethod("POST");
                    conn.setDoInput(true);
                    conn.setDoOutput(true);
                    OutputStream os = conn.getOutputStream();

                    os.close();

                    int responseCode=conn.getResponseCode();

                    if (responseCode == HttpsURLConnection.HTTP_OK) {

                        BufferedReader in=new BufferedReader(new InputStreamReader(conn.getInputStream()));
                        StringBuilder sb = new StringBuilder("");
                        String line="";
                        while ((line = in.readLine()) != null)
                        {
                            sb.append(line).append("\n");
                        }
                        result = sb.toString();
                    }

                    assert inputStream != null;
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
                    StringBuilder sb = new StringBuilder();

                    String line = null;
                    while ((line = reader.readLine()) != null)
                    {
                        sb.append(line).append("\n");
                    }
                    result = sb.toString();
                } catch (Exception e) {
                    Log.i("tagconvertstr", "["+result+"]");
                    System.out.println(e);
                }
                finally {
                    try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
                }
                return result;
            }

            @Override
            protected void onPostExecute(String result){

                myJSON = result;
                showList();

            }
        }
        GetDataJSON g = new GetDataJSON();
        g.execute();
    }



    protected void showList(){
        try {
            peoples = new JSONArray(myJSON);
            for(int i=0;i<peoples.length();i++){

                JSONObject c = peoples.getJSONObject(i);
                String name = c.getString(TAG_NAME);

                HashMap<String,String> persons = new HashMap<String,String>();

                persons.put(TAG_NAME,name);

                personList.add(persons);
            }



            ListAdapter adapter = new SimpleAdapter(
                    ListViewMultipleSelectionActivity.this, personList, R.layout.result,
                    new String[]{TAG_NAME},
                    new int[]{R.id.name}
            );




            list1.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
            list1.setAdapter(adapter);

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }



}

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

    <Button
        android:id="@+id/testbutton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:text="Submit" />

    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_above="@id/testbutton"
        android:layout_alignParentTop="true"/>

</RelativeLayout>

result.xml

<?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" >

<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/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:textStyle="bold"/>

</LinearLayout>

</LinearLayout>

i have implemented this on testbutton(Button) click please check

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

                SparseBooleanArray checked = list1.getCheckedItemPositions();
                ArrayList<String> selectedItems = new ArrayList<String>();
                for (int i = 0; i < checked.size(); i++) {
                    int position = checked.keyAt(i);
                       if (checked.valueAt(i))
                         selectedItems.add((String) adapter.getItem(position));
                }

                String[] valuess = new String[selectedItems.size()];

                for (int i = 0; i < selectedItems.size(); i++) {
                    valuess[i] = selectedItems.get(i);
                }
                Toast.makeText(ListViewMultipleSelectionActivity.this, String.valueOf(valuess), Toast.LENGTH_SHORT).show();
            }
        });

this is i am getting after click

E/-->>>>: [Ljava.lang.String;@ca01299

Upvotes: 0

Views: 1951

Answers (3)

user4156995
user4156995

Reputation:

What you can do is creating a custom class to store these values along with a custom adapter that supports it. So whenever you click the button you can call the given function to retrieve the statuses of those items. Example architecture given below:

PS: Since I don't know what you want to do with checked values, I left you there with comments which you can change with your need.

MainActivity.java

package com.rencsaridogan.stackoverflow;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

  ArrayList<ExampleClass> objects;

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

    objects = new ArrayList<>();

    for (int i = 0; i < 10; i++){
      objects.add(new ExampleClass("Example Name " + i));
    }

    final ListView listView = (ListView) findViewById(R.id.listView);
    final Button testButton = (Button) findViewById(R.id.testButton);
    final ExampleAdapter exampleAdapter = new ExampleAdapter(this, R.layout.list_cell, objects);
    listView.setAdapter(exampleAdapter);
    exampleAdapter.notifyDataSetChanged();

    testButton.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        getCheckedItems();
      }
    });

  }

  private void getCheckedItems(){
    for (int i = 0; i < 10; i++) {
      if (objects.get(i).isChecked()){
        Log.i("MainActivity",i + " is checked");
        /**
         * Value is checked, do what you need to do here
         */
      } else {
        Log.i("MainActivity",i + " is NOT checked");
        /**
         * Value is NOT checked
         */
      }
    }
  }
}

ExampleAdapter.java

package com.rencsaridogan.stackoverflow;

import android.annotation.SuppressLint;
import android.content.Context;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import java.util.ArrayList;
/**
 * Created by rencsaridogan on 16/02/2017.
 */

public class ExampleAdapter extends ArrayAdapter<ExampleClass> {

  ArrayList<ExampleClass> objects;
  Listener listener;
  Context context;

  public ExampleAdapter(Context context, int resource, ArrayList<ExampleClass> objects) {
    super(context, resource);
    this.context = context;
    this.objects = objects;
  }

  @Override public int getViewTypeCount() {
    return super.getViewTypeCount();
  }

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

  @SuppressLint("InflateParams") @Override public View getView(int position, View convertView, @NonNull ViewGroup parent) {

    if (convertView == null){
      Log.i("ExampleAdapter","ConvertView inflated");
      convertView = LayoutInflater.from(context).inflate(R.layout.list_cell, null, false);
    }

    Log.i("ExampleAdapter","Setting of values");

    final ExampleClass data = objects.get(position);
    final ViewHolder viewHolder = new ViewHolder();

    viewHolder.textView = (TextView) convertView.findViewById(R.id.textView);
    viewHolder.checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);

    viewHolder.textView.setText(data.getName());

    viewHolder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
      @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        data.setChecked(isChecked);
      }
    });

    return convertView;
  }

  public void setListener(Listener listener) {
    this.listener = listener;
  }

  private class ViewHolder {

    TextView textView;
    CheckBox checkBox;
  }

  public ArrayList<ExampleClass> getObjects() {
    return objects;
  }

  public void setObjects(ArrayList<ExampleClass> objects) {
    this.objects = objects;
    notifyDataSetChanged();
  }

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

  public interface Listener {
    void onCheckedChanged(int position);
  }
}

ExampleClass.java

package com.rencsaridogan.stackoverflow;

/**
 * Created by rencsaridogan on 16/02/2017.
 */

public class ExampleClass {
  String name;
  boolean isChecked;

  public ExampleClass(String name) {
    this.name = name;
  }

  public ExampleClass(String name, boolean isChecked) {
    this.name = name;
    this.isChecked = isChecked;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public boolean isChecked() {
    return isChecked;
  }

  public void setChecked(boolean checked) {
    isChecked = checked;
  }
}

Upvotes: 1

Neh Kumari
Neh Kumari

Reputation: 17

In your Adapter there was one @override method called getView() in that method you will get the current item which you will clicked

  holder.checkbox.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // TODO Auto-generated method stub

    CheckBox checkBox=(CheckBox) view;
      String tagName="";
     if(checkBox.isChecked()){
       tagName=checkBox.getTag().toString();
       deleteServices.add(tagName);
       checkboxArrayList.add(checkBox);
    }else {
           checkboxArrayList.remove(checkBox);
           tagName=checkBox.getTag().toString();
                if(deleteServices.size()>0&&deleteServices.contains(tagName)){

deleteServices.remove(tagName); }

        });

Upvotes: 0

Prabha Karan
Prabha Karan

Reputation: 1319

  1. Set checkbox object as tag to your row view that might be your 'convertView' in getView() method of your adapter.

  2. Write on click listener on your row view. 3.Inside that click-listener to row view getTag from view that's parameter in onClick method and cast it to checkbox and then setChecked to true for that checkbox object.

code might look like this,

  convertView.setTag(yourCheckBoxObject);
    convertView.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            CheckBox cb = (CheckBox) v.getTag();
            cb.setChecked(true);
        }
    });

Please refer this sight for more information Getting an issue while checking the dynamically generated checkbox through list view

Upvotes: 0

Related Questions