I have a listview with some elements that are saved on a database and I access them using a custom content provider.
In my main activity, I have implemented a ResourceCursorAdapter.
What I need is, when I click on a element of the list, the cursor have to access to this item's parameters and send them to another activity. I have almost this done, but I think I'm not getting right the cursor's position. The true is that I don't know how to do this, if I have to use the ID to access the item on the database, or using the position is enough.
protected void onListItemClick(ListView l, View v, int position, long id) {
Cursor cursor = getContentResolver().query(TravelsProvider.CONTENT_URI, null, null, null, null);
while(cursor.moveToPosition(position)) {
Intent intent = new Intent(this, TravelActivity.class);
intent.putExtra(TravelActivity.EXTRA_CITY, cursor.getString(cursor.getColumnIndex(Travels.CITY)));
intent.putExtra(TravelActivity.EXTRA_COUNTRY, cursor.getString(cursor.getColumnIndex(Travels.COUNTRY)));
intent.putExtra(TravelActivity.EXTRA_YEAR, cursor.getInt(cursor.getColumnIndex(Travels.YEAR)));
intent.putExtra(TravelActivity.EXTRA_NOTE, cursor.getString(cursor.getColumnIndex(Travels.NOTE)));
cursor.close();
startActivity(intent);
super.onListItemClick(l, v, position, id);
}
}
UPDATE
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Cursor cursor = ((CursorAdapter)l.getAdapter()).getCursor();
cursor.moveToPosition(position);
Intent intent = new Intent(this, TravelActivity.class);
intent.putExtra(TravelActivity.EXTRA_CITY, cursor.getString(cursor.getColumnIndex(Travels.CITY)));
intent.putExtra(TravelActivity.EXTRA_COUNTRY, cursor.getString(cursor.getColumnIndex(Travels.COUNTRY)));
intent.putExtra(TravelActivity.EXTRA_YEAR, cursor.getInt(cursor.getColumnIndex(Travels.YEAR)));
intent.putExtra(TravelActivity.EXTRA_NOTE, cursor.getString(cursor.getColumnIndex(Travels.NOTE)));
startActivity(intent);
cursor.close();
}
}
Also, this is my onCreate method:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getTravelsAdapter();
//...
}
public void getTravelsAdapter() {
Cursor c = getContentResolver().query(TravelsProvider.CONTENT_URI, PROJECTION, null, null, null);
mAdapter = new TravelsCursorAdapter(this, c);
setListAdapter(mAdapter);
}
you should be able to get the adapter through
l.getAdapter()
and safely cast the returned value to your implementation of ResourceCursorAdapter
. Than you can use getCursor
on the returned value of the previous call, and get the cursor.
Once you get the cursor you can move to position with Cursor.moveToPosition(position);
and retrieve your data
Example:
Cursor cursor = ((TravelsCursorAdapter)l.getAdapter()).getCursor();
cursor.moveToPosition(position);