我正在尝试从我的数据库中返回多行。我有两个要检索的坐标,它们存储在我的数据库中,即经度和纬度。由于我的异步任务目前只能返回一行。我应该如何更改我的代码,以便它能够从数据库返回多行?
提前感谢您的帮助。
下面是我的代码:
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;
}
while($row = mysqli_fetch_array($sql)>0){
$response["longitude"] = $row[0];
$response["latitude"] = $row[1];
die(json_encode($response));
}
异步任务类。
class Findfriends extends AsyncTask<String, String, JSONObject> {
protected JSONObject doInBackground(String... args) {
// TODO Auto-generated method stub
// here Check for success tag
try {
HashMap<String, String> params = new HashMap<>();
params.put("username", args[0]);
JSONObject json = jsonParser.makeHttpRequest(
GET_FRIENDS, "POST", params);
if (json != null) {
Log.d("JSON result", json.toString());
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(JSONObject json) {
if (json != null) {
Toast.makeText(Borrower_AP.this, json.toString(),
Toast.LENGTH_LONG).show();
try {
Longitude = json.getDouble("longitude");
Latitude = json.getDouble("latitude");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
最佳答案
我认为你必须在这里犯错,第一个是你的 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);
另一方面,在您的 Android 代码中,如果您使用的是 Google Maps Api,则可以返回一个 ArrayList,如下所示:
class Findfriends extends AsyncTask<String, String, ArrayList<LatLong> {
protected ArrayList<LatLong> doInBackground(String... args) {
// TODO Auto-generated method stub
// here Check for success tag
ArrayList<LatLong> geoPos=new ArrayList<LatLong>();
try {
HashMap<String, String> params = new HashMap<>();
params.put("username", args[0]);
JSONObject json = jsonParser.makeHttpRequest(
GET_FRIENDS, "POST", params);
if (json != null) {
Log.d("JSON result", json.toString());
//Complete here the code in which you iterate over the json and add each point to your ArrayList<LatLong>
}
} catch (Exception e) {
e.printStackTrace();
}
return geoPos;
}
}
关于android - 使用 asynctask 返回多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32696569/