How to get id from database when clicking list item in android

I have looked at various questions related to this on this website, but I cannot solve the problem that I am getting.

I want to get the id from the database when I click on a list item.

This is the class of my categories:

package com.example.reminders;

import java.util.List;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class Categories extends ListActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        DBAdapter db = new DBAdapter(Categories.this);
        db.open();
        List<String> cs = db.getAllCategoriesList();
        setListAdapter(new ArrayAdapter<String>(this, R.layout.activity_categories,cs));
        ListView listView = getListView();
        listView.setTextFilterEnabled(true);
        listView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // When clicked, show a toast with the TextView text

                 Cursor cur = (Cursor) parent.getItemAtPosition(position);
                Toast.makeText(getApplicationContext(),
                "id:"+id+"position:"+position+"rowid:"+cur.getInt(cur.getColumnIndex("_id")), Toast.LENGTH_LONG).show();
            }
        }); 
        db.close();


    }


}

The getAllCategoriesList function defined in the DBAdapter class:

//---retrieves all the category data---
    public List<String> getAllCategoriesList() 
    {
        String[] columns = new String[] {KEY_NAME2};
        Cursor c = db.query(DATABASE_TABLE2, columns, null, null, null, null,
            KEY_NAME2);     
       // String results = "";
        List<String> results = new ArrayList<String>();
        int iCM = c.getColumnIndex(KEY_NAME2);

        for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
            results.add(c.getString(iCM));
        }
        return results;

    }

When I ran the sample code, the following error appears:

10-01 15:05:22.507: E/AndroidRuntime(20846): java.lang.ClassCastException: java.lang.String cannot be cast to android.database.Cursor
+5
source share
1 answer

You do not request _id from the database (only column KEY_NAME2), so you cannot get it from the adapter.

This line:

Cursor cur = (Cursor) parent.getItemAtPosition(position);

completely wrong. You are trying to use String (which returns ArrayAdapter<String>to a cursor that can never work.

, CursorAdapter ( SimpleCursorAdapter) ListView. _id KEY_NAME2.

getItem(int position) . , , cursor.getInt(cursor.getColumnIndex("_id")), .

+6

All Articles