Mohit Mohit - 5 months ago 17
Java Question

list view not showing data accordingly when parsing json

I am parsing json to list view..The data is parsing nicely, but there is some problem in array adapter class which is not showing view accordingly.

public void parseJson(JSONObject json) {
try {
JSONArray posts = json.getJSONArray("resume");
feedList = new ArrayList<JsonItem>();
for (int i = 0; i < posts.length(); i++) {
JSONObject post = (JSONObject) posts.getJSONObject(i);
JsonItem item = new JsonItem();
JSONArray cast = post.getJSONArray("Education");
Log.i("lenght", Integer.toString(cast.length()));
if (cast != null && cast.length()>0) {
for(int j =0 ;j<cast.length();j++){
JSONObject casts = (JSONObject)cast.getJSONObject(j);
item.setTitle(casts.getString("Title"));
feedList.add(item);
Log.i("feedsize", feedList.get(j).toString());
}
}
}
}catch(JSONException e){
e.printStackTrace();
}


Json array:

{
"resume":[
{
"Education":[
{
"Title":"Post Graduation",
"Degree":"M. Tech."
},
{
"Title":"Graduation",
"Degree":"B. Tech."
}
]
}
]
}


I this array there are two title: Post Graduation , Graduation

But in layout out it is showing only one value: Graduation

output

Answer

Instantiate your JsonItem object in inner loop instead of outer, this way:

public void parseJson(JSONObject json) {
try {
        JSONArray posts = json.getJSONArray("resume");
        feedList = new ArrayList<JsonItem>();
        for (int i = 0; i < posts.length(); i++) {
            JSONObject post = (JSONObject) posts.getJSONObject(i);

            JSONArray cast = post.getJSONArray("Education");
            Log.i("lenght", Integer.toString(cast.length()));
            if (cast != null && cast.length()>0) {
                for(int j =0 ;j<cast.length();j++){                       

                   JsonItem item = new JsonItem();

                   JSONObject casts = (JSONObject)cast.getJSONObject(j);
                   item.setTitle(casts.getString("Title"));
                   feedList.add(item);
                   Log.i("feedsize", feedList.get(j).toString());
                }
            }


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