0

I‘m trying to use Http response to get data from PHP server but the tricky thing in here that I get the response as a one string. I want to put the response into array. The response originally contains many queries that I retrieved from MySQL. I am grateful for any help.

4

4 に答える 4

0

JSON データを返す php スクリプトを作成してみてください。これは、データを取得して配列に入れる例です。

<?php
 $response = array();

 require_once __DIR__ . '/db_connect.php';

$db = new DB_CONNECT();  
$result = mysql_query("SELECT * FROM tbl_products") or die(mysql_error());

if (mysql_num_rows($result) > 0) {

$response["product"] = array();

while ($row = mysql_fetch_array($result)) {

    $product            = array();
    $product["products_id"]     = $row["table_id"];
    $product["products_price"]  = $row["transaction_no"];
$product['products_name']   = $row["table_total_price"];

    array_push($response["product"], $product);
}
$response["success"] = 1;

echo json_encode($response);

} else {
$response["success"] = 0;
$response["message"] = "No products found";

echo json_encode($response);
}
?>

これはアンドロイド用です:

JSONObject json = jParser.getJSONFromUrl(NAME_OF_URL);

        Log.d("All Product List: ", json.toString());

        try {

            int success = json.getInt("success");

            if (success == 1) {

                products = json.getJSONArray("product");

                for (int i = 0; i < products.length(); i++) {

                    JSONObject c = products.getJSONObject(i);

                    String id  =c.getString("products_id");
                    String price =c.getString("products_price");
                    String name = c.getString("products_name");

                }

            } else {

            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
于 2013-09-06T08:18:35.303 に答える
0

これを試してください...応答を配列に保存するのに役立ちます。

           try
             {

                URL url = new URL("http:/xx.xxx.xxx.x/sample.php");
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                 InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                 BufferedReader r = new BufferedReader(new InputStreamReader(in));
                 String x = "";
                 String total = "";
                 int i=0;
                 ArrayList<String> content = new ArrayList();
                 while((x = r.readLine()) != null)
                 {
                             content.add(x);

                 }
                 in.close();
                 r.close();
             }
             catch(Exception e)
             {
                 e.printStackTrace();
                 Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
             }

arrayList を配列に変換できます。

              String ar[]= content.toArray(new String[content.size()]);
于 2013-09-06T06:56:46.327 に答える