How to extract values from JSONObject in android

phpnerd picture phpnerd · Apr 27, 2014 · Viewed 15k times · Source

1.I am having json object like this how can i get the access to all values in android
2.before anyone down voting that i want to say i have searched stackoverflow for similar examples but those examples contains JSONObject and then JSONArray
3.Here in my case everything is JSONObject so i'm little bit confused

{
"1":
{"sno":"10","latitude":"31.249441437085455","longitude":"75.70003598928452"},

"2":
{"sno":"11","latitude":"31.249398442090207","longitude":"75.70003397762775"}
}

This is how i made it to JSONObject
1.Below code returned me output like that which is all JSONObject
2.Is there any way to make "1" and "2" as JSONArray ?

$select_rows = "select sno,latitude,longitude from activities where username='$username'";
if ($result = mysql_query($select_rows)) {

$num_of_fields = mysql_num_fields($result);
$num_of_rows = mysql_num_rows($result);

 $i = 0;

    $j = 1;

    while ($retrieved = mysql_fetch_array($result)) {

        for ($i = 0; $i < $num_of_fields; $i++) {

            $field_name = mysql_field_name($result, $i);

            $object[$j][$field_name] = $retrieved[$field_name];
        }
        $j++;
    }
    echo json_encode($object);
}

Answer

shabeer picture shabeer · Apr 27, 2014

Hope this may help you

JSONObject jsonObject=new JSONObject(result);

            jsonObject=jsonObject.getJSONObject("1");

            Double lat=jsonObject.getDouble("latitude");




            Toast.makeText(getBaseContext(),""+ lat, Toast.LENGTH_LONG).show();