user1496980
user1496980

Reputation: 15

retrieving data from sqlite database and displaying it in another class through "OnItemClick"

I want that as I click on list item the application should load another class and then display the required data on textview by retrieving the data from sqlite database

@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);
}

this code is in WordDetails class

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")));
    }
}

When I click on an item "Error" word is being displayed which is supposed to show, but wordTd equals -1. Why this wordId is not getting correct value? Thanks for your help.

Upvotes: 1

Views: 1310

Answers (2)

Sam
Sam

Reputation: 86958

The id passed by default to the OnItemClickListener is the row's unique id from the database, there is no need to get it in this manner:

id = wordList.getItemIdAtPosition(position);

Change your OnItemClickListener to this:

@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);
}

Upvotes: 1

Squonk
Squonk

Reputation: 48871

The 'keys' used when putting Intent extras are case sensitive. You are putting the id as...

intent.putExtra("Word_ID", id);

...but then trying to get it with...

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

In other words you're putting Word_ID and trying to get WORD_ID. Change the code so they're both the same and it should work.

Upvotes: 2

Related Questions