2015-07-11 88 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