simranjazz simranjazz - 19 days ago 5
Android Question

How to set unique ID for each Item in Android ListView?

My Code:

JSONArray jArray = new JSONArray(result);
if(jArray.length() > 0) {
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
expense_id = json_data.getInt("expense_id");
client_name = json_data.getString("client_name");
expense_type = json_data.getString("expense_type");
expense_amount = json_data.getInt("expense_amount");
listItems.add(i, expense_id + "- " + client_name + " | " + expense_type + " : Rs. " + String.valueOf(expense_amount));
}
adapter=new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,listItems);
ListView list_expenses = (ListView) findViewById(R.id.list_expenses);
list_expenses.setAdapter(adapter);
registerForContextMenu(list_expenses);
list_expenses.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, final View view,int position, long id) {
final String item = (String) parent.getItemAtPosition(position);
final int extra_expense_id = Integer.parseInt(item.split("-")[0]);
Intent intent = new Intent(HomeScreenActivity.this, ViewExpenseActivity.class);
intent.putExtra(EXTRA_EXPENSE_ID, extra_expense_id);
startActivity(intent);
}
});
}


When I use onItemClick listener, I want to send 'expense_id' to the next Activity. But how do I set individual 'expense_id' for each Item?

In my code I've added expense_id in each item and then splitting it to get the id. But this is a bad approach. Any way I can set a hidden ID attribute to each listItem?

I also tried - listItem.add(expense_id, "String object here"); so that I can get the index which would be equal to expense_id.
But this work since ArrayList has to start from index 0.

Possible Answers:

1 - User Custom Adapter: No I've already implemented ArrayAdapter properly.

2 - Use setTag, getTag? That works on entire ListView object. It doesn't work on individual items.

Answer

You can create separate list for expense id.

ArrayList<Integer> expenseIds = new ArrayList<Integer>();

Added expenseId in list in for...loop

expenseIds.add(expense_id);

You can get expense_id int onItemClick method like below code

expenseIds.get(position);