2015-07-11 89 views
2

我有以下的回应,我想显示所有的eqid的个人TextView的,但我不知道如何实现这一点, 下面是我的代码段和响应从服务器获取数据和显示在textview中。
任何人都可以帮助我吗?如何访问json数组中的个别json对象?

{ 
    "earthquakes":[ 
    { 
     "eqid":"c0001xgp", 

    }, 
    { 
     "eqid":"c000905e", 

    }, 
    { 
     "eqid":"2007hear", 

    }, 
    { 
     "eqid":"c00090da", 

    }, 
    { 
     "eqid":"2007aqbk", 

    }, 
    { 
     "eqid":"2007hec6", 

    }, 
    { 
     "eqid":"a00043nx", 

    }, 
    { 
     "eqid":"2010utc5", 

    }, 

    ] 
} 

代码

ServiceHandler sh = new ServiceHandler(); 
    jsonStr = sh.makeServiceCall(USER_URL, ServiceHandler.GET); 
    Log.d("Response: ", "> " + jsonStr); 

    try{ 
     JSONObject json = new JSONObject(jsonStr); 
     JSONArray items = json.getJSONArray("product"); 

     parent_layout = (RelativeLayout)findViewById(R.id.rl); 
     for(int i =0; i<items.length(); i++){ 



      TextView textView = new TextView(this); 
      textView.setText(items.getJSONObject(i).getString(USER_NAME)); 

      parent_layout.addView(textView); 
     } 

回答

1

try{ 
 
    JSONObject json = new JSONObject(jsonstr); 
 
    JSONArray items = json.getJSONArray("earthquakes"); 
 

 
    for(int i =0; i<items.length(); i++){ 
 
     TextView t=new TextView(context); 
 
     t.setText(items.getJSONObject(i).getString('eqid')); 
 
     ParentLayout.addView(t); 
 
    } 
 
}catch(JSONException e){ 
 
    e.printStacktrace(); 
 
}

+0

看到我编辑的代码在问题..我没有任何错误..但没有任何错误..但响应不显示 – Aditya

+0

,因为你已经使用相对布局你的textview将互相重叠...尝试线性布局或添加属性,如layoutToLeftOf或以上或下面和那样.... –

1

您有一个包含单个JSON阵列中的单个JSON对象。因此,您首先从对象中检索数组,然后您可以遍历它来检索所有项目。在下面的代码中,我假设你有一个数组中的目标为TextView

try{ 
    JSONObject json = new JSONObject(jsonstr); 
    JSONArray items = json.getJSONArray("earthquakes"); 

    for(int i =0; i<items.length(); i++){ 
     textViews[i].setText(items.getJSONObject(i).getString('eqid')); 
    } 
}catch(JSONException e){ 
    e.printStacktrace(); 
} 
+0

你可以告诉一个东西? – Aditya

+0

http://stackoverflow.com/questions/18917214/change-background-colour-of-current-listview-item-in-adapter-getview-method ...在这个问题,他们chagne颜色..我可以添加按钮alternatvly – Aditya

+0

这将是一个单独的问题。问题应该留在主题上。 – TmKVU