Skip to content Skip to sidebar Skip to footer

How Do I Get The Cursor Value Of A Listview's Item Onitemclick?

I've created a database with tables (categories) with columns (_id, title etc). I want to read these categories' data from my database and list them in a ListView. Here is my code:

Solution 1:

Use CursorAdapter(http://developer.android.com/reference/android/widget/CursorAdapter.html) instead, when you are using ArrayAdapter it's exceed memory allocation, and also you wouldn't get notifications if db changed.

Moreover in case of using CursorAdapter you will have

publicvoidonItemClick(AdapterView<?> parent, View v, finalint position, long id)

the "id" param will concur with table's _id field

to get the whole row just do

adapter.getItem(int position)

Solution 2:

Instead of

int cat_id = cur.getInt(cur.getColumnIndex("_id"));
String cattitle = cur.getString(cur.getColumnIndex("title"));
int has_sub = cur.getInt(cur.getColumnIndex("has_sub"));
results.add(cat_id + cattitle + has_sub);

create a Category class to contain these values, and use a parameterized ArrayList. Something like

classCategory {
    publicint cat_id;
    public String cattitle;
    publicint has_sub;

    publicCategory(int cat_id, ...){
        // constructor logic here
    }
}

and

results.add(new Category(cat_id, cattitle, has_sub));

With this, you can set the onItemClickListener as such:

        catlist.setOnItemClickListener(newOnItemClickListener() {

           @OverridepublicvoidonItemClick(AdapterView<?> parent, View v,
             finalint position, long id) {
                 CategoryclickedCategory= results.get(position);
                 intid= clickedCategory.cat_id;

                 // do something with id
           }
          });     

Your ArrayList is the data source of your ArrayAdapter, and position corresponds to the index of the clicked Category in it.

Post a Comment for "How Do I Get The Cursor Value Of A Listview's Item Onitemclick?"