Below is my Android code which is supposed to retrieve the json array. But it shows an exception that "json array cannot be converted to json object". What is wrong with this code?
JSONObject json = new JSONObject(result);
JSONArray jArray = json.getJSONArray("emparray");
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
// testing works ...
// ... until here
for (int i = 0; i < jArray.length(); i++) {
json = jArray.getJSONObject(i);
String id = null, loc = null;
id = json.getString("user_id");
loc = json.getString("crtloc_lat");
HashMap<String,String> persons2 = new HashMap<String,String>();
persons2.put("uder_id",id);
persons2.put("crtloc_lat",loc);
personList.add(persons2);
mylist.add(persons2);
Toast.makeText(MapsActivity.this, "waw id is"+id, Toast.LENGTH_SHORT).show();
}
PHP file
<?php
require "config.php";
$con = mysqli_connect(HOST,USER,PASS,DB);
$pro_id=2;
$sql="SELECT user.user_id, current_location.crtloc_lat,current_location.crtloc_lng FROM user INNER JOIN current_location
where user.user_id=current_location.user_id AND user.pro_id='$pro_id'";
$result = mysqli_query($con, $sql) or die("Error in Selecting " . mysqli_error($con));
//create an array
$emparray[] = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode($emparray);
//close the db connection
mysqli_close($con);
?>
and the following is my json array
[[],{"user_id":"77","crtloc_lat":"34.769638","crtloc_lng":"72.361145"},{"user_id":"76","crtloc_lat":"34.769547","crtloc_lng":"72.361504"},{"user_id":"87","crtloc_lat":"33.697117","crtloc_lng":"72.976631"},{"user_id":"86","crtloc_lat":"33.697117","crtloc_lng":"72.976631"}]