I have searched through various questions related to this on this website but i am unable to resolve the issue i am getting.
I want to get id from database on click of listview item
This is my categories class:
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();
}
}
getAllCategoriesList function defined in the DBAdapter class is :
//---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 example code the following error comes:
10-01 15:05:22.507: E/AndroidRuntime(20846): java.lang.ClassCastException: java.lang.String cannot be cast to android.database.Cursor
You are not querying the _id from the database (only the KEY_NAME2 column), so you're not able to get it from the adapter.
This line:
Cursor cur = (Cursor) parent.getItemAtPosition(position);
is entirely wrong. You are trying to cast a String (which is returned by ArrayAdapter<String>
to a cursor, which can never work.
What you have to do, is use a CursorAdapter
(or SimpleCursorAdapter
) for your ListView. The cursor should query at least for _id and KEY_NAME2.
With this adapter the getItem(int position)
will return a cursor set to requested position. Then all you need to do is cursor.getInt(cursor.getColumnIndex("_id"))
and you're there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With