I'm simply trying to get the text being displayed in the ListView for the row the user clicks.
List view and adapter
ListView listCurrent = (ListView)findViewById(R.id.currentlinkslist);
try {
SQLiteOpenHelper tractionDatabaseHelper = new TractionDatabaseHelper(this);
db = tractionDatabaseHelper.getReadableDatabase();
String query = "SELECT _id, QUESTION FROM QUESTION";
cursor = db.rawQuery(query, null);
CursorAdapter listAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
cursor,
new String[]{"QUESTION"},
new int[]{android.R.id.text1},0);
listCurrent.setAdapter(listAdapter);
}catch(SQLiteException e) {
Toast.makeText(this, "Database unavailable", Toast.LENGTH_SHORT).show();
}
AdapterView.OnItemClickListener itemClickListener =
new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> listCurrent,
View v, int position, long id) {
String selectedItem = listCurrent.getItemAtPosition(position).toString();
Toast.makeText(AssociateActivity.this,
selectedItem , Toast.LENGTH_SHORT).show();
}
};
listCurrent.setOnItemClickListener(itemClickListener);
From everything I've seen, this code in the AdapterView.OnItemClickListener should fetch the description:
String selectedItem = listCurrent.getItemAtPosition(position).toString();
Toast.makeText(AssociateActivity.this, selectedItem, Toast.LENGTH_SHORT).show();
Instead, I keep getting:
What am I doing wrong?
the method getItemAtPosition()
is returning a SQLiteCursor
object and this kind of object has no implementations of the method toString()
. So in this case you have to return the cursor itself and parse it to your object before you call toString()
method.
SQLiteCursor cursor = (SQLiteCursor) listCurrent.getItemAtPosition(position);
String selectedItem = cursor.getString(columIndex); //columIndex is not the position
Toast.makeText(AssociateActivity.this, selectedItem, Toast.LENGTH_SHORT).show();