Mansour Fahad
Mansour Fahad

Reputation: 735

How to put http response into array in Android

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.

Upvotes: 0

Views: 1785

Answers (4)

Decoding Sequence
Decoding Sequence

Reputation: 26

Try to create a php scripts that return a JSON data this is the example of retrieving data and putting them into array.

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

and this one is for android:

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

Upvotes: 0

Benito Bertoli
Benito Bertoli

Reputation: 25793

You should encode your response on the server side using a data interchange format such as XML or JSON.

Then you can easily parse it on the client side.

Android has great support for both, though JSON might be a bit easier.

If your data structure is very simple - e.g a list of words - you could use CSV (Comma Separated Value) and String.split() to get an array:

String[] words = response.split(",");


JSON example (string array)

[
   "The quick brown fox jumps over the lazy dog",
   "Jackdaws love my big sphinx of quartz",
   "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut"
]


JSONArray array = new JSONArray(response);
String[] sentences = new String[array.length()];
for (int i = 0, i < array.length(); i++){
    sentences[i] = array.getString(i);
}

Upvotes: 1

Niraj Adhikari
Niraj Adhikari

Reputation: 1728

a better way would be to make your php webservice send data in JSON. then recieve it as a and parse the JSON response for data you need. I recommend JSON because it is more lighter than xml which will improve performance reducing bandwidth consumption.

Upvotes: 0

Ram
Ram

Reputation: 2530

Try this...It will help you to store your response in array.

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

You can convert the arrayList to array.

              String ar[]= content.toArray(new String[content.size()]);

Upvotes: 0

Related Questions