【问题标题】:retrieving data from sqlite database and displaying it in another class through "OnItemClick"从 sqlite 数据库中检索数据并通过“OnItemClick”将其显示在另一个类中
【发布时间】:2012-07-02 19:38:53
【问题描述】:

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

【问题讨论】:

  • 仅供参考,将代码剪切并粘贴到问题中后,再次突出显示代码并按 Ctrl+K 将其格式化为代码块。使用 ` 表示代码的 sn-ps。

标签: android sqlite


【解决方案1】:

放置Intent 附加项时使用的“键”区分大小写。您将 id 设置为...

intent.putExtra("Word_ID", id);

...但后来尝试用...得到它

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

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

【讨论】:

  • 好收获(赞成)。我虽然id 不正确,但它只是一种多余的方法......
  • 将 WORD_ID 更改为 Word_ID 后,我仍然得到相同的结果
【解决方案2】:

默认传递给 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);
}

【讨论】:

  • 这样做后我仍然得到相同的结果
  • 谢谢你告诉我。这对我很有帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多