3

我有一个连接到数据库并获取数据的 php 文件,现在我希望将这些数据发送到我的 java 代码并存储为一个数组,用于连接到 php 并检索结果我 现在在AsyncHttpClient 中使用 AsyncHttpClient他们是一个函数onSucess将字符串值作为其参数,因此来自 php 的任何内容都存储为字符串。我希望它是数组..请给我建议一种方法,要么得到一个数组而不是字符串,下面是我的代码。

 public void func3(View view)throws Exception
{
    AsyncHttpClient client = new AsyncHttpClient();
    RequestParams rp = new RequestParams();
    rp.put("pLat", "select * from iwmp_state");
    client.post("http://10.0.2.2/conc2.php", rp, newAsyncHttpResponseHandler() {
        public final void onSuccess(Array response) {
            // handle your response here
            //tx.setText(response.toString());

        }

        @Override
        public void onFailure(Throwable e, String response) {
            // something went wrong
            tx.setText(response.toString());
        }               
    });
}

我得到了一个 php 文件,它回显了一个数组$row

<?php
 // attempt a connection
 $dbh = pg_connect("host=10.22.35.11 dbname=iwmp_dev2 user=postgres "); 
 if (!$dbh) {
     die("Error in connection: " . pg_last_error());
 }       

 // execute query
 $sql = $_POST['pLat'];
 $result = pg_query($dbh, $sql);
 if (!$result) {
     die("Error in SQL query: " . pg_last_error());
 }       
$array = array();
 // iterate over result set
 // print each row
 while ($row = pg_fetch_array($result)) {
    $i++;
echo $row[0];
 }       

 // free memory
 pg_free_result($result);       

 // close connection
 pg_close($dbh);
 ?>  

什么 php echos 是数组,什么 onSuccess 作为参数是字符串。该怎么办!

4

3 回答 3

5

在这里,我只是展示简单的演示。您必须根据您的要求进行更新。

PHP端

创建简单PHP Array,更多详情请点击这里

<?php
$cars=array("Volvo","BMW","Toyota");
$arrlength=count($cars);

for($x=0;$x<$arrlength;$x++)
  {
  echo $cars[$x];
  echo "<br>";
  }
 echo json_encode($cars); 
 exit;
?>

安卓端

现在如何在 android 中读取 PHP 数组?

String String_Response = ""; // this is your web response

创建一个ArrayList.

    ArrayList<String> User_List = new ArrayList<String>();


                  try
              {
            JSONArray jArray = new JSONArray(String_Response);
            for (int i = 0; i < jArray.length(); i++)
            {
                       JSONObject json_data = jArray.getJSONObject(i);                                                        
               User_List.add(json_data.getString("your_json_obj"));
            }

               } 
                  catch (Exception e)
              {
            Log.e(TAG, "" + e);
               }

另请查看下面的链接,您将更了解如何从 android 向 php 发送和接收数据。

Android + PHP 通信示例

于 2013-04-26T11:14:00.167 回答
1

明白了,我们可以做的是在我们的 php 中使用一个IMPLODE函数,并在每个数组值之后添加 (,),然后让它作为字符串传递。在java代码中使用它之后。String 的split(",") func 并将它们存储在一个数组中。

对我来说工作得很好。不需要json:P

于 2013-04-26T11:45:37.993 回答
1

我很难理解您希望实现的目标,但也许我可以提供一些帮助:将您的 php 数组插入一个字符串(http://php.net/manual/en/function.implode.php)然后在至少您可以看到您返回的内容并可能在客户端重新处理它?

于 2013-04-26T11:04:44.027 回答