从sqlite数据库中检索数据并通过“OnItemClick”将其显示在另一个类中

时间:2012-07-02 19:38:53

标签: android sqlite

我希望当我点击列表项时,应用程序应该加载另一个类,然后通过从sqlite数据库中检索数据在textview上显示所需的数据

@Override
public void onItemClick(AdapterView<?> parent, View view,
        int position, long id) {
    // TODO Auto-generated method stub
    Intent intent = new Intent(DictionaryActivity.this,
            WordDetails.class);
    // Cursor cursor = (Cursor) adapter.getItem(position);
    id = wordList.getItemIdAtPosition(position);
    intent.putExtra("Word_ID", id);
    // cursor.getInt(cursor.getColumnIndex("_id"));
    startActivity(intent);
}

此代码位于WordDetails类

wordId = getIntent().getIntExtra("WORD_ID", -1);
if (wordId == -1) {
    mean = (TextView) findViewById(R.id.mean);
    mean.setText("Error");
} else {
    SQLiteDatabase db = (new DatabaseHelper(this))
            .getReadableDatabase();
    Cursor cursor = db.rawQuery(
            "SELECT _id ,word, mean FROM Meanings WHERE _id = ?",
            new String[] { "" + wordId });
    if (cursor.getCount() == 1) {
        cursor.moveToFirst();
        mean = (TextView) findViewById(R.id.mean);
        mean.setText(cursor.getString(cursor.getColumnIndex("mean")));
    }
}

当我点击一个项目“错误”时,显示的单词应显示,但wordTd等于-1。为什么这个wordId没有得到正确的价值?谢谢你的帮助。

2 个答案:

答案 0 :(得分:2)

添加Intent个附加功能时使用的“键”区分大小写。你把id作为......

intent.putExtra("Word_ID", id);

...但是后来试着用它来......

wordId = getIntent().getIntExtra("WORD_ID", -1);

换句话说,你放Word_ID并试图获得WORD_ID。更改代码,使它们都相同,它应该可以工作。

答案 1 :(得分:1)

默认情况下传递给OnItemClickListener的id是数据库中行的唯一ID,不需要以这种方式获取它:

id = wordList.getItemIdAtPosition(position);

将OnItemClickListener更改为:

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    Intent intent = new Intent(DictionaryActivity.this, WordDetails.class);
    intent.putExtra("Word_ID", id);
    startActivity(intent);
}