0

I am writing an App in which i am fetching data into ListView using JSON, and i already fetched data for first Level (eventName), but getting blank activity while fetching for second Level (angelName) ...

JSON:-

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

In short, unable to get 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);
                    }
                });
            }
        }
    }
Sun
  • 6,768
  • 25
  • 76
  • 131

4 Answers4

1

It appears that you're not fetching a JSONArray at the right level.

The JSONArray arrayAngels that you get is actually an array containing only one element. To get an array containing the angels, you need to go deeper:

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

The first JSONArray you fetch from your data is an array of one element, containing everything. The first (and only) JSONObject contained in that array still contains all your data. It's only when you get the JSONArray from that object that you get to what you want.

Edit: A full code sample:

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

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

jsonData also contains eventName data if you wanted to also use that. Note that getJSONArray() throws an exception if it can't find the key you want, so it might be better to use optJSONArray, which returns null if the key isn't in the data.

LeoR
  • 369
  • 1
  • 9
1

Try this,

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;
            }
SathishKumar
  • 1,644
  • 1
  • 14
  • 28
  • @Abrahim Neil Welcome – SathishKumar Nov 25 '13 at 12:02
  • getting first event's Angel Name for all Events, like EventA (AngelA, AngelB) , EventB (AngelC, AngelD). so i am getting AngelA & AngelB either i do tap on EventA or EventB, why? – Sun Nov 25 '13 at 12:36
  • sorry can not get your problem, – SathishKumar Nov 25 '13 at 12:57
  • like EventName is Honda Motors, having two Angels Angel A, B as you can see in my above JSON, i have another Event in my JSON namely Tata Motors, this event has two more Angels namely Angel C, Angel D .... whenever i do tap on Tata Motors getting Angel A, Angel B in a List, instead of showing Angel C, Angel D...I hope now you are getting my issue – Sun Nov 25 '13 at 13:01
  • check this: http://stackoverflow.com/questions/20212289/fetch-json-data-into-list – Sun Nov 26 '13 at 09:41
0

Try this..

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));
        }
}
Hariharan
  • 24,741
  • 6
  • 50
  • 54
0

you have to frist get Json array "angelList" after that you can get angelName value.

JSONArray arra = new JSONArray(json);

JSONObject jobj=arra.getJSONObject(0);

   arrayAngels = jobj.getJSONArray("angelList");
navneet sharma
  • 680
  • 4
  • 7