问题
I have this class, that gets the data from the database and shows in a listview.
Is there a way to get the Id from the database and toast it?
Now the toast is returning: android.database.sqlite.SQLiteCursor@4180c088
public class AndroidSQLite extends Activity {
private SQLiteAdapter
mySQLiteAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView listContent = (ListView)findViewById(R.id.contentlist);
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToRead();
Cursor cursor = mySQLiteAdapter.queueAll();
startManagingCursor(cursor);
String[] from = new String[]{SQLiteAdapter.KEY_NOME,SQLiteAdapter.KEY_ID};
int[] to = new int[]{R.id.text,R.id.id};
SimpleCursorAdapter cursorAdapter =
new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
listContent.setAdapter(cursorAdapter);
listContent.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
//GET ID FROM DATABASE
Toast.makeText(getBaseContext(), parent.getItemAtPosition(position).toString(), Toast.LENGTH_LONG).show();
//THIS TOAST IS RETURNING "android.database.sqlite.SQLiteCursor@4180c088"
}
});
mySQLiteAdapter.close();
} }
回答1:
Simply use the id
parameter of onItemClick()
:
Toast.makeText(getBaseContext(), id + "", Toast.LENGTH_LONG).show();
For future reference you are currently trying to use an entire Cursor as a String, you want to select a column like this:
Toast.makeText(getBaseContext(), parent.getItemAtPosition(position).getLong(0), Toast.LENGTH_LONG).show();
(For a SimpleCursorAdapter the first column is always the _id
column, hence getLong(0)
.)
来源:https://stackoverflow.com/questions/13126481/get-id-from-database-in-a-listview-onclick