【问题标题】:Return multiple values using asynctask使用 asynctask 返回多个值
【发布时间】:2015-12-18 05:35:10
【问题描述】:

我正在尝试从我的数据库中返回多行。我有两个要检索的坐标,它们存储在我的数据库中,即经度和纬度。由于我的 asynctask 目前只能返回一行。我应该如何更改我的代码以便它能够从数据库中返回多行?

提前感谢您的帮助。

以下是我的代码:

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));
    }

Asynctask 类。

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();
            }
        }
    }
}

【问题讨论】:

  • 只返回一个你想要返回的元素列表。
  • 只需创建一个模型来保存您想要返回的数据。
  • 您可以返回 jsonarray 或返回行列表
  • @KishuDroid 有没有例子说明如何做?
  • @IngoSchwarz 有什么进一步的解释吗?

标签: android mysql android-asynctask


【解决方案1】:

我认为你必须在这里犯错,第一个是你的 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;
    }


}

【讨论】:

  • 认为我也需要更改解析器,对吗?因为我正在使用 JSONParser 来处理数据,但我不太确定如何更改它以返回数组
【解决方案2】:

请像这样更改 php 脚本,

$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(mysqli_num_rows($sql)>0)
{
while($row = mysqli_fetch_array($sql)
   {
   $latlongArray =array();
   $latlongArray ["longitude"] = $row[0];
   $latlongArray ["latitude"] = $row[1];
   array_push($response["DATA"],$latlongArray) 
   }
$response["success"] = "1";
echo json_encode($response);
}
else
{ 
 $response["success"] = "0";
 echo json_encode($response);
}

在 android 代码中,在 Post 执行粘贴此代码,在 logcat 中,您将看到数据库中的 lat / longs。

 JSONArray ja = json.getJSONArray("DATA");
 for (int r = 0; r < ja.length(); r++) {
 JSONObject obj = ja.getJSONObject(r);
 Log.i("Lat / Long",obj.getString("latitude")+" , "+obj.getString("longitude"));
 }

试试这个它可能对你有帮助.. 它是有效的代码。 谢谢,

【讨论】:


  • 警告:array_push() 期望参数 1 为数组,/home/u524163630/public_html/check_if_friends.php中给出的 null > 第 30 行
    {"DATA":null,"success":"1"}。我得到了这个错误。知道为什么吗?
【解决方案3】:

像这样创建自己的处理程序:

//import android.os.Handler; this import is required.
public class MyHandler extends Handler{

   public void handleMessage(Message msg) {
       super.handleMessage(msg);
       List<YourObject> objs=(List<YourObject>)msg.obj;     
   }

}

在您的活动中创建异步对象,如下所示:

MyDataFetcher mdf=new MyDataFetcher(new MyHandler());

像这样写你的异步:

class MyDataFetcher extends AsyncTask<String, String, JSONObject> {
    private Handler handler
    public MyDataFetcher(Handler handler){
        this.handler=handler;
    }

    //here is code you need to write in onPost
   protected void onPostExecute(JSONObject json) {
        if (json != null) {
            Toast.makeText(Borrower_AP.this, json.toString(),
                    Toast.LENGTH_LONG).show();
            try {
                List<YourObject> objs=new ArrayList<>();
                // populate your info from json into objs
                //------your code here for above logic
                //Now create new Message 
                Message msg=new Message();
                msg.obj=objs;
                handler.handleMessage(msg);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-20
    • 2016-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多