How to get object value from listview adapter position

Dave Jackson picture Dave Jackson · Jan 18, 2013 · Viewed 61k times · Source

How to get value from adapter position, i have code in below:

CategoriesXmlParser categoryXmlParser = new CategoriesXmlParser();
List<HashMap<String, Object>> categories = null;

try {
  categories = categoryXmlParser.parse(reader);
} catch (Exception e) {
  Log.d("Exception", e.toString());
}

String[] from = { "name", "image" };
int[] to = { R.id.nama_category, R.id.logo_category };

final SimpleAdapter adapter = new SimpleAdapter(getBaseContext(),
                    categories, R.layout.per_item_category, from, to);

mListView.setOnItemClickListener(new OnItemClickListener() {
  public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {
    Object obj = mListView.getAdapter().getItem(position);
    String value = obj.toString();
    Log.d("MyLog", "Value is: "+value);
    String name = // how code to get name value.
  }
});

If I look log it on logcat in the MyLog I get as:

Value is: {position=12, image_path=http://192.168.103.121/xml/icon.png, link=http://192.168.103.121/xml/category.php?kat_id=13, name=Category 13}

So my question, I want to get value from name and stored to variable String name, I want to get just "Category 13" in String name. Because I want to passing it to another activity.

Answer

user1068963 picture user1068963 · Jan 18, 2013

Looks like you made ​​the object with hashmap, such blablabla.put("name", "value")?? If yes. Try this:

mListView.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view,
            int position, long id) {
        Object obj = mListView.getAdapter().getItem(position);
        String value = obj.toString();
        Log.d("MyLog", "Value is: "+value);
        String name = // how code to get name value.
    }
});

Change to:

mListView.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        HashMap<String, Object> obj = (HashMap<String, Object>) adapter.getItem(position);
            String name = (String) obj.get("name");
            Log.d("Yourtag", name);
    }
});