我正在写一个JSONArray
,以便从我的Android应用程序的数据库中返回多个数据。
我编写了以下代码,但它根本没有返回任何数据,因为此行的错误为java.lang.NullPointerException
:jArray = new JSONArray(result);
如何更改代码以便JSONArray
有效?对JSONArray
的工作方式不太确定。
提前感谢您的帮助!
php文件:
$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类:
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();
}
答案 0 :(得分:0)
尝试在功能IOUtils.ToString()
中构建以将流转换为字符串
InputStream is = new InputStream(is, "iso-8859-1");
String result= IOUtils.toString( is );
jArray = new JSONArray(result);
答案 1 :(得分:0)
我会尝试将php的最后一行更改为:
print json_encode(Array("Posts" => $rows));
并将Java修改为:
//paring data
Double longitude, latitude;
try {
JSONObject object = new JSONObject(result);
jArray = object.getJSONArray("Posts"); // get specific array from php.
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();
}