1

我希望当我单击列表项时,应用程序应该加载另一个类,然后通过从 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没有得到正确的价值?谢谢你的帮助。

4

2 回答 2

2

放置Intent额外内容时使用的“键”区分大小写。您将 id 设置为...

intent.putExtra("Word_ID", id);

...但后来试图得到它...

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

换句话说,您正在投入Word_ID并试图获得WORD_ID. 更改代码,使它们都相同并且应该可以工作。

于 2012-07-02T19:54:49.553 回答
1

默认情况下id传递给 OnItemClickListener 的是数据库中行的唯一 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);
}
于 2012-07-02T19:47:09.820 回答