从SimpleAdapter获取值到array []

时间:2013-12-27 14:23:44

标签: java android

是否可以将值从SimpleAdapter转移到array[]。我从SimpleAdapter ArrayList<HashMap<String, String>>获取了值,并希望将这些值从SimpleAdapter传递给array[]

static ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();

SimpleAdapter adapter = new SimpleAdapter(this, contactList,R.layout.list_item,new String[] {android_H_NAME}, new int[] {R.id.name});

String[] hospFields = //want to get values here from adapter

2 个答案:

答案 0 :(得分:1)

修改并使用:

 ArrayList<String> listItems = new ArrayList<String>();
for (int i = 0; i < result.length(); i++) {
    try {
        listItems
                .add(result.getJSONObject(i)
                        .getString(BsharpConstant.NAME_CONSTANT)
                        .toString());
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

在oncreate方法中:

ListView list = (ListView) findViewById(R.id.idOfUrView);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
 ActivityName.this,
 android.R.layout.simple_list_item_1, listItems);
 list.setAdapter(adapter);
             list.setOnItemClickListener(this);//if u need this until not required

使用此想要在项目点击中存储值:

 @Override
  public void onItemClick(AdapterView<?> parent, View view, int position,
  long id) {
 String clickedItemName = (String) listOfProductsCategory
    .getItemAtPosition(position);
   int clickedItemId = (int) listOfProductsCategory
    .getItemIdAtPosition(position);
 // implement your login to store the value
     //by using for loop listItems[i] ,i++
   Toast.makeText(this.getActivity(),
       "Custom text : " + clickedItemName,
      Toast.LENGTH_SHORT).show();
    //call your method if u want

}

答案 1 :(得分:0)

不可能直接访问数据,但您可以使用(通常):

Object[] o = new Object[adapter.getCount()];
for (int i = 0; i < adapter.getCount(); i++) {
    o[i] = adapter.getItem(i);
}

创建适配器数据的副本。如果您只想提取特定值,请使用:

String[] hospFields = new String[adapter.getCount()];
for (int i = 0; i < adapter.getCount(); i++) {
    HashMap<String, String> rowData = adapter.getItem(i); //gets HashMap of a specific row
    String name = rowData.get("name"); //gets the field name of that row
    hospFields[i] = name; // copies field into your array
}