我在数据库中有一个列_id
我希望在单击列表视图项时获得此ID。目前,以下代码为我提供了项目的position
。我'我还在玩弄它我感觉方法有问题' getItemId'
onCreate方法
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;
}
}
答案 0 :(得分:1)
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);
}
然后在你的onItemClick
中yourCategoryId = arrayIds.get(position);
您需要在onCreate
之前在顶部声明ArrayList arrayIds