I am working on an example application for learning Android. It is assumed that it displays a list with several choices, and when the user clicks a button, it should display the elements selected in the TextView at the top. It appears that when I try to retrieve the selected items from a ListView, an empty array is always returned. Can someone explain to me why this is so and what I am missing to make it work correctly? (FYI code is a modified program from Beginning Android 4 from Grant Allen)
Here is the XML layout file:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:id="@+id/selection" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/getSelections" android:text="Show Selections" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="listSelected" /> <ListView android:id="@android:id/list" android:layout_width="fill_parent" android:layout_height="fill_parent" android:drawSelectorOnTop="false" android:choiceMode="multipleChoice" /> </LinearLayout>
And here is the related Java:
package com.commonsware.android.checklist; import android.os.Bundle; import android.app.ListActivity; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.view.*; public class ChecklistDemo extends ListActivity { private static final String[] items={"lorem", "ipsum", "dolor", "sit", "amet", "consectetuer", "adipiscing", "elit", "morbi", "vel", "ligula", "vitae", "arcu", "aliquet", "mollis", "etiam", "vel", "erat", "placerat", "ante", "porttitor", "sodales", "pellentesque", "augue", "purus"}; private TextView selection; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, items)); selection = (TextView)findViewById(R.id.selection); } public void listSelected(View view) { long[] chosenOnes = getListView().getCheckedItemIds(); selection.setText("Items selected: "); selection.setText(Integer.toString(chosenOnes.length)); for (long x:chosenOnes) { int i = Long.valueOf(x).intValue(); selection.setText(selection.getText() + ", " + items[i]); } } }