How to use Cursor Loader to access retrieved data?

*爱你&永不变心* 提交于 2019-12-05 19:47:45

It seems like you have two questions here... so I'll answer them both. Correct me if I misunderstood your question...

  1. 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();
    
  2. 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!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!