Get Selected Item Using Checkbox in Listview
Assuming you want to get items of row whose check boxes are checked at the click of a button. Assumption based on your title "Get Selected Item Using Checkbox in Listview when I click a Button".
Try the below. Make only changes as below. Keep the rest the same.
Explanation and discussion on the topic @
https://groups.google.com/forum/?fromgroups#!topic/android-developers/No0LrgJ6q2M
MainActivity.java
public class MainActivity extends Activity {
AppInfoAdapter adapter ;
AppInfo app_info[] ;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ListView listApplication = (ListView)findViewById(R.id.listApplication);
Button b= (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
StringBuilder result = new StringBuilder();
for(int i=0;i<adapter.mCheckStates.size();i++)
{
if(adapter.mCheckStates.get(i)==true)
{
result.append(app_info[i].applicationName);
result.append("\n");
}
}
Toast.makeText(MainActivity.this, result, 1000).show();
}
});
ApplicationInfo applicationInfo = getApplicationInfo();
PackageManager pm = getPackageManager();
List<PackageInfo> pInfo = new ArrayList<PackageInfo>();
pInfo.addAll(pm.getInstalledPackages(0));
app_info = new AppInfo[pInfo.size()];
int counter = 0;
for(PackageInfo item: pInfo){
try{
applicationInfo = pm.getApplicationInfo(item.packageName, 1);
app_info[counter] = new AppInfo(pm.getApplicationIcon(applicationInfo),
String.valueOf(pm.getApplicationLabel(applicationInfo)));
System.out.println(counter);
}
catch(Exception e){
System.out.println(e.getMessage());
}
counter++;
}
adapter = new AppInfoAdapter(this, R.layout.listview_item_row, app_info);
listApplication.setAdapter(adapter);
}
}
activity_main.xml ListView with button at the buton
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ListView
android:layout_width="fill_parent"
android:id="@+id/listApplication"
android:layout_height="fill_parent"
android:layout_above="@+id/button1"
android:text="@string/hello_world" />
<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" />
</RelativeLayout>
AppInfoAdapter
public class AppInfoAdapter extends ArrayAdapter<AppInfo> implements CompoundButton.OnCheckedChangeListener
{ SparseBooleanArray mCheckStates;
Context context;
int layoutResourceId;
AppInfo data[] = null;
public AppInfoAdapter(Context context, int layoutResourceId, AppInfo[] data){
super(context, layoutResourceId,data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
mCheckStates = new SparseBooleanArray(data.length);
}
@Override
public View getView(int position, View convertView, ViewGroup parent){
View row = convertView;
AppInfoHolder holder= null;
if (row == null){
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new AppInfoHolder();
holder.imgIcon = (ImageView) row.findViewById(R.id.imageView1);
holder.txtTitle = (TextView) row.findViewById(R.id.textView1);
holder.chkSelect = (CheckBox) row.findViewById(R.id.checkBox1);
row.setTag(holder);
}
else{
holder = (AppInfoHolder)row.getTag();
}
AppInfo appinfo = data[position];
holder.txtTitle.setText(appinfo.applicationName);
holder.imgIcon.setImageDrawable(appinfo.icon);
// holder.chkSelect.setChecked(true);
holder.chkSelect.setTag(position);
holder.chkSelect.setChecked(mCheckStates.get(position, false));
holder.chkSelect.setOnCheckedChangeListener(this);
return row;
}
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 AppInfoHolder
{
ImageView imgIcon;
TextView txtTitle;
CheckBox chkSelect;
}
}
Here's the snap shot
VB.net listview checkbox get selected item
It sounds like you are wanting to get the checked property but are instead setting the selected property. Try this:
For Each item As ListViewItem In Me.listAwal.Items
If item.Checked Then
'Do something with this item
End If
Next
Get checked items from ListView with check box
boolean bulkflag = false;
ListView reportslistview = (ListView) findViewById(android.R.id.list);
public class MyAdapter extends SimpleAdapter {
//private List<Table> tables;
SharedPreferences prefs;
private Activity activity;
String val = "";
//@SuppressWarnings("unchecked")
public MyAdapter(Activity context, List<? extends Map<String, String>> tables, int resource, String[] from,
int[] to) {
super(context, tables, resource, from, to);
//this.tables = (List<Table>) tables;
activity = context;
}
public View getView(final int position, final View convertView, ViewGroup parent) {
View row = super.getView(position, convertView, parent);
if (row == null)
{
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.reports_list, null);
}
final CheckBox cBox=(CheckBox)row.findViewById(R.id.cb1);
if(bulkflag)
{
cBox.setVisibility(View.VISIBLE);
}
else
{
cBox.setVisibility(View.GONE);
}
cBox.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(cBox.isChecked())
{
selectedIds.add(recIdArr.get(reportslistview.getPositionForView(cBox)));
//System.out.println("position "+reportslistview.getPositionForView(cBox));
}
else
{
selectedIds.remove(recIdArr.get(reportslistview.getPositionForView(cBox)));
}
}
});
return row;
}
}
Checking ====>
for(int i=0;i<selectedIds.size();i++)
{
System.out.println("delete multiple"+selectedIds.size()+" "+Integer.parseInt(selectedIds.get(i)));
}
Declare selectedIds
as a global variable
Getting selected Items from a ListView | CheckBoxListCell
Use this way
public void start(Stage primaryStage) {
try {
ListView<String> listView = new ListView<>();
Button button = new Button("Get");
List<String> list = new ArrayList<>();
String[] toppings = { "Cheese", "Pepperoni", "Black Olives" };
listView.getItems().addAll(toppings);
listView.setCellFactory(CheckBoxListCell.forListView(new Callback<String, ObservableValue<Boolean>>() {
@Override
public ObservableValue<Boolean> call(String item) {
BooleanProperty observable = new SimpleBooleanProperty();
observable.addListener((obs, wasSelected, isNowSelected) -> {
if (isNowSelected) {
list.add(item);
} else {
list.remove(item);
}
});
return observable;
}
}));
button.setOnAction(e -> {
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
});
VBox root = new VBox();
root.setAlignment(Pos.CENTER);
root.getChildren().addAll(listView, button);
Scene scene = new Scene(root, 300, 250);
primaryStage.setScene(scene);
primaryStage.show();
} catch (Exception e) {
e.printStackTrace();
}
}
How to get selected items in listview with checkbox on button click
You could try using SparseBooleanArray to get the selected items (from positions).
Similar stackoverflow questions with relevant answers:
- How to get Selected items from Multi Select List View
- How to get all checked items from a ListView?
How do I get all the selected list Items using Checkbox
The below code working fine for me so you can try this
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/select_btn"
android:text="Select"/>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/listview"/>
list_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="4dp"
android:orientation="horizontal" >
<CheckBox
android:id="@+id/cbBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical" >
</CheckBox>
<TextView
android:layout_height="wrap_content"
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_gravity="center_vertical"
android:ellipsize="marquee" />
Service
import java.io.Serializable;
public class Service implements Serializable
{
private static final long serialVersionUID = 1L;
private String name;
private boolean selected;
public Service() {
// TODO Auto-generated constructor stub
}
public Service(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public void setName(String name) {
this.name = name;
}
}
ServiceAdapter
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class ServiceAdapter extends BaseAdapter {
ArrayList<Service> actorList;
LayoutInflater vi;
Context context;
public ServiceAdapter(Context context,ArrayList<Service> objects) {
this.context= context;
this.vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.actorList = objects;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
// convert view = design
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = vi.inflate(R.layout.list_row, null);
holder.tvName = (TextView) convertView.findViewById(R.id.textView1);
holder.checkBox = (CheckBox) convertView.findViewById(R.id.cbBox);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.tvName.setText(actorList.get(position).getName());
holder.checkBox.setChecked(actorList.get(position).isSelected());
holder.checkBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean isSelected = ((CheckBox)v).isChecked();
actorList.get(position).setSelected(isSelected);
}
});
return convertView;
}
static class ViewHolder {
public TextView tvName;
public CheckBox checkBox;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return actorList.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return actorList.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public ArrayList<Service> getSelectActorList(){
ArrayList<Service> list = new ArrayList<>();
for(int i=0;i<actorList.size();i++){
if(actorList.get(i).isSelected())
list.add(actorList.get(i));
}
return list;
}
}
MainActivity
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ListView listView = (ListView)findViewById(R.id.listview);
listView.setAdapter(new ServiceAdapter(this,sampleData()));
Button btn = (Button)findViewById(R.id.select_btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ArrayList<Service> actorList = ((ServiceAdapter)listView.getAdapter()).getSelectActorList();
Toast.makeText(MainActivity.this,""+actorList.size(),Toast.LENGTH_LONG).show();
}
});
}
public ArrayList<Service> sampleData(){
ArrayList<Service> dataList = new ArrayList<>();
for(int i=0;i<30;i++){
Service servic = new Service();
servic.setName("Test"+i);
dataList.add(servic);
}
return dataList;
}
}
How to get a list of selected items from a listview with checkboxes? (Without code behind)
Should I add a bool property display in the "category" model and bind it to the checkbox?
Yes.
If yes, I still don't know how to get a list of all thicked items.
Just filter them out from the courseCategories
collection, for example using LINQ:
var checkedItems = courseCategories.Where(x => x.YourBoolProperty).ToArray():
Related Topics
Determine If Android App Is Being Used For the First Time
Set Up Device For Development (? No Permissions)
Android - Cancel Asynctask Forcefully
Android Chrome Ignoring -Webkit-Text-Size-Adjust:None Property. Text Is Being Scaled When Zoomed Out
Failed to Load Appcompat Actionbar with Unknown Error in Android Studio
Error "The Connection to Adb Is Down, and a Severe Error Has Occurred."
Android App Out of Memory Issues - Tried Everything and Still at a Loss
You Have Not Accepted the License Agreements of the Following Sdk Components
Singleton Object Becomes Null After App Is Resumed
How to Change Spinner Text Size and Text Color
Checkbox in Recyclerview Keeps on Checking Different Items
How to Read Mms Data in Android
Noclassdeffounderror For Code in an Java Library on Android
Updating Google Play Services in Emulator
Include .So Library in APK in Android Studio
Clear the Entire History Stack and Start a New Activity on Android