Abserve Tech Abserve Tech - 5 months ago 22
Android Question

Last json value is displayed in expandableistview in android

I have created the expandable list view. It contains parent and child items. The parent and child value is retrieved from the Json. The child item is loading fine but only the last value from Json is displayed in parent items. What to do for displaying all items in parent?

class AsyncT1 extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://abservetechdemo.com/projects/android/food_app/public/mobile/restaurant/resdetails");

try {

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("res_id","1"));
// nameValuePairs.add(new BasicNameValuePair("status","veg"));
nameValuePairs.add(new BasicNameValuePair("main_cat",childname));

// nameValuePairs.add(new BasicNameValuePair("group_id", group_id));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.e("mainToPost", "mainToPost" + nameValuePairs.toString());


/* execute */

// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
InputStream inputStream = response.getEntity().getContent();
InputStreamToStringExample str = new InputStreamToStringExample();
String responseServer = str.getStringFromInputStream(inputStream);
Log.d("response", "response -----" + responseServer);

JSONObject jsonRootObject = new JSONObject(responseServer);
JSONObject jsonobject = jsonRootObject.getJSONObject("restaurants");

JSONObject questionMark = jsonRootObject.getJSONObject("restaurants");
Iterator keys = questionMark.keys();
Log.d("key--", String.valueOf(keys));

while(keys.hasNext()) {
// loop to get the dynamic key
String k = (String)keys.next();

Group gru = new Group();
gru.setName(k);
// do something here with the value...
final ArrayList<Group> list = new ArrayList<Group>();
ArrayList<Child> ch_list;
ch_list = new ArrayList<Child>();
JSONArray ja = questionMark.getJSONArray(k);


for (int i = 0; i < ja.length(); i++) {

JSONObject jo = ja.getJSONObject(i);

Child ch = new Child();
ch.setName(jo.getString("item_name"));
ch_list.add(ch);
} // for loop end


gru.setItems(ch_list);
list.add(gru);
getActivity(). runOnUiThread(new Runnable() {
@Override
public void run() {
adapter = new ExpandListAdapter(
getActivity(), list);
ExpandList.setAdapter(adapter);

}});

}

} catch (Exception e) {
e.printStackTrace();
}
return null;
}

@Override
protected void onPostExecute(String aVoid) {
super.onPostExecute(aVoid);

}
}

Answer

Do it like this :

class AsyncT1 extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {

    //YOUR CODE

    try 
    {
        // YOUR CODE
        Log.d("key--", String.valueOf(keys));

        // better to initialize main list out side any loop so it will 
        //not get initialized with every iteration of loop..!!

        final ArrayList<Group> list = new ArrayList<Group>();

        while (keys.hasNext()) {
            // loop to get the dynamic key
            String k = (String) keys.next();
            Group gru = new Group();
            gru.setName(k);
            // do something here with the value...
            ArrayList<Child> ch_list;
            ch_list = new ArrayList<Child>();
            JSONArray ja = questionMark.getJSONArray(k);

            for (int i = 0; i < ja.length(); i++) {

                JSONObject jo = ja.getJSONObject(i);

                Child ch = new Child();
                ch.setName(jo.getString("item_name"));
                ch_list.add(ch);
            } // for loop end
            gru.setItems(ch_list);
            list.add(gru);
        }
        // set the adapter after the loop has finished the execution
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                adapter = new ExpandListAdapter(
                        getActivity(), list);
                ExpandList.setAdapter(adapter);
            }
        });

    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

@Override
protected void onPostExecute(String aVoid) {
    super.onPostExecute(aVoid);

}
}

Here // YOUR CODE means you do not need to change the code which is already there in your code.

Changes i have made mainly includes : You do not need to set the adapter inside while loop let the list have all it's data initialized then we will set the adapter outside while loop