简体   繁体   中英

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

in your onclick listener:

cursor.moveToPosition(position);
String drinkString = cursor.getString(cursor.getColumnIndexOrThrow(" *column name* "));
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()

You can do as follows:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM