2013-03-21 70 views
0

获得价值我有一个列表view.when任何一个单击它显示列表内容的列表作为从列表视图

{first_name=abc, last_name=xyz, id=1, address=kolkata} 

,但我想那些单独获得这些值从字符串谁得到这一点。

我onListItemClick听者

protected void onListItemClick(ListView l, View v, int position, long id) 
{ 
    super.onListItemClick(l, v, position, id); 
    Object o = this.getListAdapter().getItem(position); 
    String return_data = o.toString(); 

    Toast.makeText(this, ""+return_data, Toast.LENGTH_LONG).show(); 

} 

添加总类,包括列表适配器

public class showUserInfoListActivity extends ListActivity { 

ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>(); 
static final String KEY_ID   = "id"; 
static final String KEY_FIRST_NAME = "first_name"; 
static final String KEY_LAST_NAME = "last_name"; 
static final String KEY_ADDRESS = "address"; 


@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.add_user_info_list); 

    //---get all Records--- 
    DataBaseAdapter db = new DataBaseAdapter(this); 
    db.open(); 
    Cursor c = db.getAllRecords(); 
    if (c.moveToFirst()) 
    { 
     do 
     {   
      HashMap<String, String> map = new HashMap<String, String>(); 
      // adding each child node to HashMap key => value 
      map.put(KEY_ID, c.getString(0)); 
      map.put(KEY_FIRST_NAME, c.getString(1)); 
      map.put(KEY_LAST_NAME, " "+c.getString(2)); 
      map.put(KEY_ADDRESS, c.getString(3)); 

      // adding HashList to ArrayList 
      menuItems.add(map); 
     } while (c.moveToNext()); 
    } 
    db.close(); 

    // Adding menuItems to ListView 
    // All filed data are not shown in the list KEY_ID is hidden 
    ListAdapter adapter = new SimpleAdapter(this, menuItems,R.layout.user_info_list_item, 
          new String[] { KEY_FIRST_NAME, KEY_LAST_NAME, KEY_ADDRESS, KEY_ID }, 
          new int[] {R.id.first_name , R.id.last_name, R.id.address}); 
    setListAdapter(adapter); 
} 


//On select from the list show data 
protected void onListItemClick(ListView l, View v, int position, long id) 
{ 
    super.onListItemClick(l, v, position, id); 
    Object o = this.getListAdapter().getItem(position); 
    //String return_data = o.toString(); 
    MyClass return_data = (MyClass)o; 
    Toast.makeText(this, ""+return_data, Toast.LENGTH_LONG).show(); 
} 

class MyClass{ 

} 

}

回答

1

而不是

String return_data = o.toString(); 

您需要将o投射到任何类别的对象。

MyClass return_data = (MyClass)o; 

然后,您可以像往常一样访问其字段并调用其方法。

你的情况:

HashMap<String, String> returndata = (HashMap<String, String>) o; 
+0

应在return_data类 – Anirban 2013-03-21 01:38:09

+1

“MyClass的”应该是什么与任何项目的类你把到ListAdapter更换。你还没有分享过这个代码,所以我不知道它是什么类。 – 2013-03-21 01:40:21

+0

我添加了ListAdapter – Anirban 2013-03-21 01:47:28