I'm a little confused about how to use the cursor to access the data that I need using the CursorLoader model. I was able to use a SimpleCursorAdapter and pass the cursor to the swapCursor method of the adapter within the onLoadFinished method that you have to implement as follows.
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
facilityAdapter.swapCursor(cursor);
}
Now I need to query the database and based on the number of rows returned display an integer. How do I access this information? There is some information that I would like to store (the _id) of certain rows selected so that I can bundle it up and pass it to the next activity, because the id is a foreign key in other database tables and I'll need to to query the database. On the android developer site I've seen that there are accesor methods to the cursor class such as cursor.getInt, cursor.getString, etc etc, should I be using these to access the data that I am after.
It seems like you have two questions here... so I'll answer them both. Correct me if I misunderstood your question...
To get the number of rows in the table, you perform a simple query as follows:
Cursor cur = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
int numColumns = cur.getCount();
cur.close();
Retrieving the id of a selected item is actually very simple, thanks to Android adapters. Here's an example that outlines how you might pass an id to another Activity (for example, when a ListView item is clicked).
public class SampleActivity extends Activity implements
LoaderManager.LoaderCallbacks<Cursor> {
// pass this String to the Intent in onListItemClicked()
public static final String ID_TAG = "id_tag";
private SimpleCursorAdapter mAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* setup layout, initialize the Loader and the adapter, etc. */
setListAdapter(mAdapter);
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
final Intent i = new Intent(getApplicationContext(), NewActivity.class);
i.putExtra(ID_TAG, id);
// pass the id to NewActivity. You can retrieve this information in
// the Activity's onCreate() method with something like:
// long id = getIntent().getLongExtra(SampleActivity.ID_TAG, -1);
startActivity(i);
}
}
You'll have to create a URI yourself to query the foreign database. This can be done with something like:
Uri uri = Uri.withAppendedPath(CONTENT_URI, String.valueOf(id));
where CONTENT_URI
is the appropriate CONTENT_URI for your ContentProvider
.
Let me know if that helps!