2010-09-16 67 views
0

我试图在Android应用程序中填充ListView。我有JsonArray中的数据,但它不能直接使用JsonArray。任何建议如何填充ListView?如何将JSONArray放入Android ListView中

JSONObject json = null; 
    try { 
     json = new JSONObject(client.getResponse()); 
     JSONArray nameArray = json.names(); 
     JSONArray valArray = json.toJSONArray(nameArray); 

    } catch (JSONException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

    setListAdapter(new ArrayAdapter<String>(this, 
     android.R.layout.simple_list_item_1, valArray)); 

我想要“valArray”,但它不起作用。 另外我想知道valarray包含什么? (JsonArray,它包含什么)

回答

2

ArrayAdapter<String>适用于字符串。您不能将其用于JSONArray。

我认为你必须实现自定义适配器列表。尝试扩展ListAdapter的子类之一或谷歌的“自定义列表视图适配器”。 JSONArray可能包含对象(JSONObjects,其他JSONArray,字符串,布尔值,整数,长整数,双精度值,空或空)的任意组合。

3

刚刚实现了JSONArrayAdapter以将JSON数据导入ListView。它扩展了android.widget.SimpleAdapter并且与其父类非常相似。

它只有一个JSONArray转换为用于初始化所述SimpleAdapter一个List<Map<String, String>>一个静态方法。

import ... 

public class JSONArrayAdapter extends SimpleAdapter { 

    public JSONArrayAdapter(Context context, JSONArray jsonArray, 
          int resource, String[] from, int[] to) { 
     super(context, getListFromJsonArray(jsonArray), resource, from, to); 
    } 

    // method converts JSONArray to List of Maps 
    protected static List<Map<String, String>> getListFromJsonArray(JSONArray jsonArray) { 
     ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>(); 
     Map<String, String> map; 
     // fill the list 
     for (int i = 0; i < jsonArray.length(); i++) { 
      map = new HashMap<String, String>(); 
      try { 
       JSONObject jo = (JSONObject) jsonArray.get(i); 
       // fill map 
       Iterator iter = jo.keys(); 
       while(iter.hasNext()) { 
        String currentKey = (String) iter.next(); 
        map.put(currentKey, jo.getString(currentKey)); 
       } 
       // add map to list 
       list.add(map); 
      } catch (JSONException e) { 
       Log.e("JSON", e.getLocalizedMessage()); 
      } 


     } 
     return list; 
    } 


} 

只要使用同样的方式为内置Android适配器一样SimpleCursorAdapter用绳子(您的JSON数据的密钥)的映射整数(你的意见的ListView行)。请参阅documentation of SimpleAdapter