Reputation: 2773
I am making kind of big application, and it consist mostly of 3 activities and ListView components in them.
MainActivity -> FirstActivity and back
MainActivity -> SecondActivty and back
All three have ListView component inside listing their specific list view items.
I have a Singleton class called MyMachine which holds all properties of the machine inside and some of them are calculated when the main activity is created.
What I want to achieve here is list all related properties of the machine in the Main, First and Second activities . Its like categorizing properties of same thing in 3 groups.
The problem I faced is:
I want a click event on each ListView item. But the listener gives me integer key of the ListView item, which means every property of the machine need to be mapped with certain integer key. But if what is item 1 for FirstActivity is item 0 for Main activity I get wrong values printed when clicked.
Is there a better way to do this?
Basically, how to map string values and properly show them in dialog window when ListView item is clicked across all activities. I can develop functions for this certain purpose but is there a more simple way :)
Upvotes: 0
Views: 258
Reputation: 29436
ListView
shows data using Adapter
( usually one of the implementations like BaseAdapter
, SimpleAdapter
or ArrayAdapter
is used).
Adapter
class holds the references to items to be shown and also has a special method getItemId(int position)
, which has to return an ID for an item at a position in ListView.
So, lets say we have am Item class:
public class Property{
public final long id;
public final String name;
public final long price;
public Property(long id, String name, long price){
this.id = id;
this.name = name;
this.price = price;
}
}
Mapped to some database record:
| _id | name | price |
|-----|------|-------|
| 1 | abcd | 123 |
| 2 | efgh | 456 |
Then we can use an ArrayAdpater
to show a set of Property
items in a ListView
:
public class PropertyAdapter extends ArrayAdapter<Property>{
public PropertyAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
@Override
public long getItemId(int position) {
return getItem(position).id;
}
}
And you can get item's id:
ListView listView = <some list view>;
PropertyAdapter propertyAdapter = < adapter for list view >;
listView.setAdapter(propertyAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
int itemId = propertyAdapter.getItemId(i);
//-- this item Id is same as returned by getItemId(),
//-- which is id field of Property class
//-- which is id column in database
}
});
Upvotes: 1