I know this question was asked 4 years ago, but none of the answers helped me. I am following along in a book (Apress's Android Pro 5) trying to get this project to work. However, the mandatory book is outdated.
I have a simple ListView with a button on the bottom. Each list view item has a checkbox next to it. When the button is clicked it should say "ListView is checked at position ".
Everything loads, visually, just fine. But, when I follow the book's instructions, the button does nothing. When I follow any instructions from the Get listview item position on button click article, the application crashes when the button is clicked. Please note, my code below is everything I have. There aren't any other methods or anything else. Here is my code:
//Main part of code setting things up
public class MainActivity extends AppCompatActivity {
private ListView listView1;
private Button button1;
private ArrayAdapter<String> listAdapter1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView1 = (ListView) findViewById(R.id.listView1);
String[] someColors = new String[]{"Red", "Orange", "Yellow", "Green",
"Blue", "Indigo", "Violet", "Black", "White"};
ArrayList<String> colorArrayList = new ArrayList<String>();
colorArrayList.addAll(Arrays.asList(someColors));
listAdapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_checked, colorArrayList);
listView1.setAdapter(listAdapter1);
//Add the checkboxes
listView1.setChoiceMode(listView1.CHOICE_MODE_MULTIPLE);
//Here is the onItemClickListener for the list view
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int
position, long id) {
String itemValue = (String)
listView1.getItemAtPosition(position);
Toast.makeText(getApplicationContext(), itemValue,
Toast.LENGTH_LONG).show();
}
});
}
//Here is the action that is not responding at all. It literally does not make anything happen when run.
public void doClick(View view) {
int count = listView1.getCount();
SparseBooleanArray viewItems = listView1.getCheckedItemPositions();
for (int i = 0; i < count; i++) {
if(viewItems.get(i)){
String selectColor = (String)listView1.getItemAtPosition(i);
Log.v("List View", selectColor + "is checked at position" + i);
}
}
}
And for good measure, here is my XML:
<LinearLayout
android:layout_width="368dp"
android:layout_height="492dp"
android:orientation="vertical"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp">
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="62dp"
android:text="@string/sub"
android:onClick="doClick"
/>
</LinearLayout>