Question

Please can i really need you help with this code , Am using loopj.com/android-async-http To communicate with the server, everything works fine but have been trying to loop through the json object i get from the server.

{"rows":[{"Fname":"Eb\'rahim","Lname":"Durosimi","Predictions":"4","Cpredictions":"3","Points":"15"},{"Fname":"Otunba","Lname":"Alagbe","Predictions":"5","Cpredictions":"2","Points":"10"},{"Fname":"Olamide","Lname":"Jolaoso","Predictions":"4","Cpredictions":"2","Points":"10"},{"Fname":"g","Lname":"ade","Predictions":"1","Cpredictions":"1","Points":"5"},{"Fname":"Tiamiyu","Lname":"waliu","Predictions":"1","Cpredictions":"1","Points":"5"}]}

But have not bin able to get it right,Have tried different examples but to no avail.

 public void onSuccess(String content) {
            // TODO Auto-generated method stub
            super.onSuccess(content);
            try {
                JSONObject json = new JSONObject(content);
                JSONObject leaders= json.getJSONObject("rows");
                Log.d("leaders",leaders.toString());
                for(int i=0;i<leaders.length(); i++){
                    String fname = leaders.getString("Fname");
                    Log.d("First Names",fname);
                }

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

Thanks for your help

Was it helpful?

Solution

Try this..

{ ==> JSONObject and [ ==> JSONArray

try {
    JSONObject json = new JSONObject(content);
    JSONArray leaders= json.getJSONArray("rows");
    Log.d("leaders",leaders.toString());
    for(int i=0;i<leaders.length(); i++){
        JSONObject jsonas = leaders.JSONObject(i);
        String fname = jsonas.getString("Fname");
        Log.d("First Names",fname);
    }
} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

OTHER TIPS

This way you can store all data received from the webservice to a arraylist of hashmaps.

ArrayList<HashMap<String,String>> alist=new ArrayList<HashMap<String,String>>();

    try {
    JSONObject json = new JSONObject(content);          
    JSONArray jArray = json.getJSONArray("rows");
                JSONObject json_data = null;
                for (int i = 0; i < jArray.length(); i++) {
                    json_data = jArray.getJSONObject(i);
                    String fname = json_data.getString("Fname");
    String lname = json_data.getString("Lname");                
                    HashMap<String, String>map=new HashMap<String, String>();
                    map.put("Fname",Fname);
                    map.put("LName", Lname);
                    alist.add(map);
                }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top