I am writing a JSONArray
so as to return multiple data from the database for my android application.
I wrote the below code but it is not returning me any data at all as the error is java.lang.NullPointerException
at this line: jArray = new JSONArray(result);
How can I change my code so that JSONArray
works? Not very sure about how JSONArray
works.
Thanks for the help in advance!
php file:
$user=$_POST["username"];
$query = "SELECT longitude,latitude FROM friends INNER JOIN coordinates ON friends.username = coordinates.username WHERE friends.friend_of='$user'";
$sql=mysqli_query($conn, $query);
if (!$sql) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$rows = array();
while($r = mysqli_fetch_assoc($sql)) {
$rows[] = $r;
}
print json_encode($rows);
JSONArray class:
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
nameValuePairList.add(new BasicNameValuePair("username", username));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://powerbankk.16mb.com/check_if_friends.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairList));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection" + e.toString());
}
//convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
//paring data
Double longitude, latitude;
try {
jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
longitude = json_data.getDouble("longitude");
latitude = json_data.getDouble("latitude");
System.out.println(longitude);
System.out.println(latitude);
}
} catch (JSONException e1) {
Toast.makeText(getBaseContext(), "Location not found", Toast.LENGTH_LONG).show();
}