Reputation: 1
In the below code I am making a string array and splitting the string to strip out the IDs. Instead of this I want associative array so that I can select ID of the item from array. Can anyone help !
String[] data={"12__Item 1","14__Item 2","34__Item 3","56__Item 4"};
lv = (ListView)findViewById(R.id.leaning_path_list_view);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.learning_path_single_row,R.id.textView,data);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item =(String)parent.getItemAtPosition(position);
String[] parts = item.split("__");
Toast.makeText(getApplicationContext(),
"ID: " + parts[0]+" Title: " + parts[1], Toast.LENGTH_LONG)
.show();
}
});
Upvotes: 0
Views: 4305
Reputation:
Try this:
public class YourItem {
private String title;
private long id;
public YourItem(long id, String title){
this.setTitle(title);
this.setId(id);
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
@Override
public String toString(){
return title;
}
}
Call your adapter like this:
YourItem[] data={new YourItem(12,"Item 1"),
new YourItem(14,"Item 2")
new YourItem(34,"Item 3")
new YourItem(56,"Item 4")
};
ArrayAdapter<YourItem> adapter = new ArrayAdapter<YourItem>(this,R.layout.learning_path_single_row,R.id.textView,data);
And in your Listener do something like this:
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String title= parent.getItemAtPosition(position).getTitle();
long id = parent.getItemAtPosition(position).getId()
Toast.makeText(getApplicationContext(),
"ID: " + id +" Title: " + title, Toast.LENGTH_LONG)
.show();
}
});
I think it should do it.
Upvotes: 1