我在本网站上搜索了与此相关的各种问题,但我无法解决我遇到的问题。
我想在单击列表视图项时从数据库中获取 id
这是我的类别课程:
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();
}
}
DBAdapter 类中定义的 getAllCategoriesList 函数是:
//---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;
}
当我运行示例代码时,出现以下错误:
10-01 15:05:22.507: E/AndroidRuntime(20846): java.lang.ClassCastException: java.lang.String cannot be cast to android.database.Cursor