Search code examples
androiddatabasesqlitesimplecursoradapter

Android SimpleCursorAdapter ID from Database


I'm having somewhat of an issue in an application I'm developing. So, all my tables have _id fields for primary keys, and I use SimpleCursorAdapter to bind them to ListViews and Spinners. What I wanted to know is how can I make the ListView or Spinner selected item have the same ID as the corresponding row?

The strange thing is that this works with the ContextMenu, which I am using straight of the NotePad example:

AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
info.id

This ID field IS the same as the RowID on the table, and I can delete items fine, but when I try something like this:

getListView().setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> adapter, View view,
                int position, long arg) {
            Intent i = new Intent(getApplicationContext(),
                    FuelingList.class);
            long id = view.getId();

The ID field is some random rubberish. So my question is, in the first code bit, what Id is the AdapterContextMenuInfo getting and how can I retrieve it in other parts of my code?


Solution

  • Since you are using a SimpleCursorAdapter, the onItemClick is passing the database row id in to you..

            public void onItemClick(AdapterView<?> adapter, View view, int position, long arg)  
    

    The long arg part is actually your row id from the database.

    So your code should be:

    getListView().setOnItemClickListener(new OnItemClickListener() { 
         public void onItemClick(AdapterView<?> adapter, View view, 
                int position, long arg) { 
            Intent i = new Intent(getApplicationContext(), 
                    FuelingList.class); 
            long id = arg;