Paula Daniela
Paula Daniela

Reputation: 115

How to properly get JSONArray Items?

I have a php file where i retrieve data from a db, then convert it to an array, and then encode it, so the Android app I'm developing gets the JSONArray parse it, and get the data.

This is the php file:

<?php

$response = array();

// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();
$dbh = $db->connect(); // here you get the connection

$query = "SELECT *FROM lost_pets";

$result = $dbh->prepare($query);
$result->execute();

if ($result->fetchAll() > 0) {
     foreach($dbh->query($query) as $row){
        $pet["id"] = $row['id'];
        $pet["name"] = $row['name'];
        $pet["breed"] = $row['breed'];

        $response["pet"] = array($pet);
        echo json_encode($response);
     }
}
?>

This is the result:

{"pet":[{"id":"1","name":"Prueba","breed":"Yorkshire Terrier"}]}{"pet":[{"id":"2","name":"Prueba2","breed":"German Shepherd"}]}{"pet":[{"id":"3","name":"Prueba3","breed":"Beagle"}]}

The problem is, when I retrieve the JSONObject in Android, and do getJSONArray(), instead of giving me 3 arrays i just get the above result.

I really don't have a very good understanding of PHP but following the php documentation I don't see what I am doing wrong. I'm very close to finish the app, this is the only big problem I couldn't solve by now, and it is really upsetting me. Thanks!

EDIT: JSONParser

else if(method.equals("GET")){
        // request method is GET

        if (sbParams.length() != 0) {
            url += "?" + sbParams.toString();
        }

        try {
            urlObj = new URL(url);
            conn = (HttpURLConnection) urlObj.openConnection();
            conn.setDoOutput(false);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept-Charset", charset);
            conn.setConnectTimeout(15000);
            conn.connect();
            is = conn.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + '\n');
            }
            is.close();
            json = sb.toString();
            System.out.println(json.toString() + "This is the json");
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

//             try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }catch (NullPointerException ex){
            System.out.println("No internet");
        }

        return jObj;

    }

    conn.disconnect();
    return jObj;
}

Upvotes: 1

Views: 144

Answers (3)

samrat shakya
samrat shakya

Reputation: 135

You need array_push where $pet pushed in array and print that array. use,

<?php
 $arr=array();
 foreach($dbh->query($query) as $row){
    $pet["id"] = $row['id'];
    $pet["name"] = $row['name'];
    $pet["breed"] = $row['breed'];
    $response["pet"] = array_push($arr,$pet); 
 }

 print_r($arr);

?>

Upvotes: 2

Dinith Rukshan Kumara
Dinith Rukshan Kumara

Reputation: 680

I used below function in all my apps to get data from php & json arrays. Try this.

public void ParseJsonArray(json){ //json is the json array you got. pass it to this function. this can get specific data from json array.

try {
        JSONArray jsonArray = json.getJSONArray("pet"); //get all data
        int count = 0;

//if you have more columns & you want to get specific columns.   
        while (count<jsonArray.length()){

            JSONObject JO = jsonArray.getJSONObject(count); //get data row by row.
            String s1 = JO.getString("id"); //get id value to string s1. 
            String s2 = JO.getString("name"); //get name to string s2. 
            String s3 = JO.getString("breed"); //get breed to string s3.            
            count++;        }

    } catch (JSONException e) {
        e.printStackTrace();  }
    }

Upvotes: 1

jeroen
jeroen

Reputation: 91762

You need to encode the final array structure once, encoding in your loop results in invalid json in the end as you will have multiple concatenated json strings.

The easiest way to get that, is to select only the fields you want:

$query = "SELECT id, name, breed FROM lost_pets";

$result = $dbh->prepare($query);
$result->execute();

echo json_encode($result->fetchAll(PDO::FETCH_ASSOC));
exit;

If you need a pet or pets key somewhere inbetween, you might need a loop but you can assign the rows at once just the same; no need to assign the individual fields.

Upvotes: 1

Related Questions