2013-11-25 157 views
0

我正在寫一個應用程序,我正在使用JSON將數據提取到ListView中,並且我已經爲第一級(eventName)獲取數據,但在獲取第二級(angelName)時獲取空白活動...使用JSON獲取數據

JSON: -

[ 
    { 
    "eventName" : "Honda Motors", 
    "angelList" : [ 
    { 
    "angelID": "1", 
     "angelName": "Angel A" 
    }, 
    { 
    "angelID": "2", 
     "angelName": "Angel B" 
    } 
    ] 
    } 
] 

總之,無法得到AngelName,

AngelsActivity.java:-

public class AngelsActivity extends ListActivity { 
    // Connection detector 
     ConnectionDetector cd; 

     // Alert dialog manager 
     AlertDialogManager alert = new AlertDialogManager(); 

     // Progress Dialog 
     private ProgressDialog pDialog; 

     // Creating JSON Parser object 
     JSONParser jsonParser = new JSONParser(); 

     ArrayList<HashMap<String, String>> angelsList; 

     // albums JSONArray 
     JSONArray arrayAngels = null; 

     // Category name 
     String category_Name; 

     // ALL JSON node names 
     private static final String ANGEL_NAME = "angelName"; 

     @Override 
     public void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.activity); 

      cd = new ConnectionDetector(getApplicationContext()); 

      // Check for internet connection 
      if (!cd.isConnectingToInternet()) { 
       // Internet Connection is not present 
       alert.showAlertDialog(AngelsActivity.this, "Internet Connection Error", 
         "Please connect to working Internet connection", false); 
       // stop executing code by return 
       return; 
      } 

      // Hashmap for ListView 
      angelsList = new ArrayList<HashMap<String, String>>(); 

      // Loading Albums JSON in Background Thread 
      new LoadAlbums().execute(); 

      // get listview 
      ListView lv = getListView(); 

      /** 
      * Listview item click listener 
      * TrackListActivity will be lauched by passing album id 
      * */ 
      lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() { 
       @Override 
       public void onItemClick(AdapterView<?> arg0, View view, int arg2, 
         long arg3) { 

       } 
      });  
     } 

     /** 
     * Background Async Task to Load all Albums by making http request 
     * */ 
     class LoadAlbums extends AsyncTask<String, String, String> { 

      /** 
      * Before starting background thread Show Progress Dialog 
      * */ 
      @Override 
      protected void onPreExecute() { 
       super.onPreExecute(); 
       pDialog = new ProgressDialog(AngelsActivity.this); 
       pDialog.setMessage("Listing Angels ..."); 
       pDialog.setIndeterminate(false); 
       pDialog.setCancelable(false); 
       pDialog.show(); 
      } 

      /** 
      * getting Categories JSON 
      * */ 
      protected String doInBackground(String... args) { 
       // Building Parameters 
       List<NameValuePair> params = new ArrayList<NameValuePair>(); 

       // getting JSON string from URL 
       String json = jsonParser.makeHttpRequest(EventsActivity.URL_CATEGORIES, "GET", 
         params); 

       try {    
        arrayAngels = new JSONArray(json); 

        if (arrayAngels != null) { 

         // looping through All albums 
         for (int i = 0; i < arrayAngels.length(); i++) { 
          JSONObject c = arrayAngels.getJSONObject(i); 

          // Storing each json item values in variable 
          String name = c.getString(ANGEL_NAME); 

          // creating new HashMap 
          HashMap<String, String> map = new HashMap<String, String>(); 

          // adding each child node to HashMap key => value 
          map.put(ANGEL_NAME, name);       

          // adding HashList to ArrayList 
          angelsList.add(map); 
         } 
        }else{ 
         Log.d("Angels: ", "null"); 
        } 

       } catch (JSONException e) { 
        e.printStackTrace(); 
       } 

       return null; 
      } 

      /** 
      * After completing background task Dismiss the progress dialog 
      * **/ 
      protected void onPostExecute(String file_url) { 
       // dismiss the dialog after getting all albums 
       pDialog.dismiss(); 
       // updating UI from Background Thread 
       runOnUiThread(new Runnable() { 
        public void run() { 
         /** 
         * Updating parsed JSON data into ListView 
         * */ 
         ListAdapter adapter = new SimpleAdapter(
           AngelsActivity.this, angelsList, 
           R.layout.list_item, 
           new String[] {ANGEL_NAME}, 
           new int[] {R.id.category_name }); 

         // updating listview 
         setListAdapter(adapter); 
        } 
       }); 
      } 
     } 
    } 

回答

1

試試這個,

protected String doInBackground(String... args) { 
       List<NameValuePair> params = new ArrayList<NameValuePair>(); 

       // getting JSON string from URL 
       String json = jsonParser.makeHttpRequest(EventsActivity.URL_CATEGORIES, "GET", 
         params); 

       try {    
        arrayAngels = new JSONArray(json).getJSONObject(0).getJSONArray("angelList"); 

        if (arrayAngels != null) { 

         // looping through All albums 
         for (int i = 0; i < arrayAngels.length(); i++) { 
          JSONObject c = arrayAngels.getJSONObject(i); 

          // Storing each json item values in variable 
          String name = c.getString(ANGEL_NAME); 

          // creating new HashMap 
          HashMap<String, String> map = new HashMap<String, String>(); 

          // adding each child node to HashMap key => value 
          map.put(ANGEL_NAME, name);       

          // adding HashList to ArrayList 
          angelsList.add(map); 
         } 
        }else{ 
         Log.d("Angels: ", "null"); 
        } 

       } catch (JSONException e) { 
        e.printStackTrace(); 
       } 

       return null; 
      } 
+0

做的感謝...非常coolll ...非常需要和太容易 – Sun

+0

@Abrahim Neil歡迎 – SathishKumar

+0

獲得所有事件的第一個事件的天使名稱,如EventA(AngelA,AngelB),EventB(AngelC,AngelD)。所以我得到AngelA&AngelB,或者我點擊EventA或EventB,爲什麼? – Sun

0

試試這個..

for (int i = 0; i < arrayAngels.length(); i++) { 
     JSONObject c = arrayAngels.getJSONObject(i); 

     // Storing each json item values in variable 
     String name = c.getString(ANGEL_NAME); 
     JSONArray angels = c.getJSONArray("angelList"); 
     for (int j = 0; j < angels.length(); j++) { 
      JSONObject c1 = arrels.getJSONObject(j); 
      Log.v("angelName",c1.getString(ANGEL_NAME)); 
     } 
} 
+0

仍然沒有得到,請給我一些更多的代碼 – Sun

1

看來,你沒有在合適的水平取出一個JSONArray。

你得到的JSONArray arrayAngels實際上是一個只包含一個元素的數組。要獲得包含天使的數組,你需要更進一步:

JSONArray allAngels = arrayAngels.getJSONObject(0).getJSONArray("angelList"); 

您從數據讀取第一JSONArray是一種元素的數組,其中包含的一切。該數組中包含的第一個(也是唯一的)JSONObject仍包含所有數據。只有當你從這個對象中得到JSONArray時,你才能得到你想要的。

編輯:完整的代碼示例:

JSONObject jsonData = new JSONArray(json).getJSONObject(0); 
arrayAngels = jsonData.optJSONArray("angelList"); 

if (arrayAngels != null) { 
    // Code to process arrayAngels 
} 

jsonData還包含eventName的數據,如果你想同時使用。請注意,如果getJSONArray()找不到所需的密鑰,則會引發異常,所以最好使用optJSONArray,如果該密鑰不在數據中,則返回null。

+0

請您能不能告訴我在哪裏,我在我的代碼中使用這條線的方式.... – Sun

0

您必須首先獲取Json數組「angelList」,然後您才能獲得angelName值。

JSONArray arra = new JSONArray(json); 

JSONObject jobj=arra.getJSONObject(0); 

    arrayAngels = jobj.getJSONArray("angelList");