How to get the selected item from ListView?
Solution 1:
By default, when you click on a ListView item it doesn't change its state to "selected". So, when the event fires and you do:
myList.getSelectedItem();
The method doesn't have anything to return. What you have to do is to use the position and obtain the underlying object by doing:
myList.getItemAtPosition(position);
Solution 2:
You are implementing the Click Handler rather than Select Handler. A List by default doesn't suppose to have selection.
What you should change, in your above example, is to
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
MyClass item = (MyClass) adapter.getItem(position);
}
Solution 3:
Since the onItemClickLitener()
will itself provide you the index of the selected item, you can simply do a getItemAtPosition(i).toString()
. The code snippet is given below :-
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String s = listView.getItemAtPosition(i).toString();
Toast.makeText(activity.getApplicationContext(), s, Toast.LENGTH_LONG).show();
adapter.dismiss(); // If you want to close the adapter
}
});
On the method above, the i
parameter actually gives you the position of the selected item.
Solution 4:
On onItemClick :
String text = parent.getItemAtPosition(position).toString();