John Long
John Long

Reputation: 67

How to get String value of item clicked in listview in Android

Here is my database query and SimpleCursorAdapter setup:

db = stockDatabaseHelper.getReadableDatabase();

            final Cursor cursor = db.rawQuery("SELECT _id, name FROM types", null);

            SimpleCursorAdapter listAdapter = new SimpleCursorAdapter(
                    this,
                    android.R.layout.simple_list_item_1,
                    cursor,
                    new String[] { StockDatabaseContract.StockType.COLUMN_NAME_NAME },
                    new int[] { android.R.id.text1 },
                    0);
            lvTypes.setAdapter(listAdapter);

Here is the on click code:

 AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(TypeSelection.this, BrandSelection.class);

                String selectedType = parent.getItemAtPosition(position).toString();

                intent.putExtra(BrandSelection.TYPE_NAME, selectedType);
                startActivity(intent);
            }
        };

I only seem to get a value such as android.database.sqlite.SQLiteCursor@435b9ba0 but need just the value of the item in the list like Vodka or Whiskey

Upvotes: 0

Views: 267

Answers (3)

Haider Malik
Haider Malik

Reputation: 1771

in your onclick listener:

cursor.moveToPosition(position);
String drinkString = cursor.getString(cursor.getColumnIndexOrThrow(" *column name* "));

Upvotes: 1

Mehmed
Mehmed

Reputation: 3040

You can do as follows:

Cursor cursor = (Cursor) parent.getItemAtPosition(position);
// Index for name column is 1
String selectedType = cursor.getString(1);

Upvotes: 0

Anupam
Anupam

Reputation: 2853

AdapterView.OnItemClickListener onItemClickListener = new 
AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(TypeSelection.this, BrandSelection.class);

               String selectedType = parent.getItemAtPosition(position).getDrinksName.toString();

                intent.putExtra(BrandSelection.TYPE_NAME, selectedType);
                startActivity(intent);
        }
    };

Try using like this -

getItemAtPosition(position).getDrinksName.toString()

Upvotes: 0

Related Questions