Devil Raily Devil Raily - 20 days ago 4
Android Question

Get the id from listview when an item is clicked

I have a column in the database

_id
I would like to get this id when an list view item is clicked. Currently the code below is giving me the
position
of the item. I' am still playing around with it I have a feeling something is wrong in the method 'getItemId'

onCreate method

ArrayList<String> arrayCatNames = new ArrayList<String>();
String query = "SELECT * FROM category ORDER BY name ASC";
Cursor results = myDB.rawQuery(query, null);
while(results.moveToNext()){
String catName = results.getString(results.getColumnIndex("name"));
arrayCatNames.add(catName);
}
String[] catNamesArr = new String[arrayCatNames.size()];
catNamesArr = arrayCatNames.toArray(catNamesArr);
lvActivityCategory = (ListView) findViewById(R.id.lvActivityCategory);
lvActivityCategory.setAdapter(new categoryCursorAdaptor(this, catNamesArr));
lvActivityCategory.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getApplicationContext(), categoryActivity.class);
intent.putExtra("category_id", id);

Context context = getApplicationContext();
String s = Long.toString(position);
CharSequence text = s;
int duration = Toast.LENGTH_SHORT;

Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
});


categoryCursorAdaptor

class categoryCursorAdaptor extends BaseAdapter {

Context context;
String[] data;
private static LayoutInflater inflater = null;

public categoryCursorAdaptor(Context context, String[] data) {
this.context = context;
this.data = data;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public int getCount() {
return data.length;
}

@Override
public Object getItem(int position) {
return data[position];
}

@Override
public long getItemId(int position) {
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (vi == null) vi = inflater.inflate(R.layout.item_category, null);
TextView text = (TextView) vi.findViewById(R.id.itemListCategory);
text.setText(data[position]);
return vi;
}
}

Answer
ArrayList<String> arrayCatNames = new ArrayList<String>();
ArrayList<Integer> arrayIds = new ArrayList<Integer>();
String query = "SELECT * FROM category ORDER BY name ASC";
Cursor results = myDB.rawQuery(query, null);
while(results.moveToNext()){
            String catName = results.getString(results.getColumnIndex("name"));
            int Ids = results.getInt(results.getColumnIndex("_id"));
            arrayCatNames.add(catName);
            arrayIds.add(Ids);
}

Then in your onItemClick

yourCategoryId = arrayIds.get(position);

You need to declare your ArrayList arrayIds at the top, before your onCreate

Comments