Reputation: 1
i am getting this error using php-mysql and json, seriously i have spent 2 days, so here is my codes
require "includes/connexion.php";
$requete="SELECT * FROM contacts;";
$rep=$pdo->query($requete);
while($data=$rep->fetch(PDO::FETCH_ASSOC)){
$sortie[]=$data;
}
print(json_encode($sortie));
$rep->closeCursor();
here is a part of the java code and the jsonArray in the results parameter contains that value(from the console):
[{"id":"1","nom":"Fedson Dorvilme","email":"[email protected]","phone":"34978238","img":"ic_launcher"},{"id":"2","nom":"Darlene Aurelien","email":"[email protected]","phone":"34171191","img":"ic_launcher"}]
JSONArray array = new JSONArray(result);
for (int i = 0; i < array.length(); i++) {
JSONObject json_data = array.getJSONObject(i);
Log.i("MyLogFlag", "Nom Contact: " + json_data.getString("nom"));
returnString = "\n\t" + array.getJSONArray(i);
System.out.println(" ********** RS [ "+returnString+" ]****************");
}
} catch (Exception e) {
Log.e("log_Exception_tag", "Error parsing data " + e.toString());
}
thanks in advance for your help
Upvotes: 0
Views: 841
Reputation: 77910
This is your json structure:
[
{
"id": "1",
"nom": "Fedson Dorvilme",
"email": "[email protected]",
"phone": "34978238",
"img": "ic_launcher"
},
{
"id": "2",
"nom": "Darlene Aurelien",
"email": "[email protected]",
"phone": "34171191",
"img": "ic_launcher"
}
]
From your Java code:
JSONArray array = new JSONArray(result); // OK
for (int i = 0; i < array.length(); i++) {
JSONObject json_data = array.getJSONObject(i); // OK
returnString = "\n\t" + array.getJSONArray(i); // ??? wrong!!
}
You try to get Array from array but its JSONObject
.
Proper way:
JSONArray gb = new JSONArray(str);
for (int j = 0; j < gb.length(); j++) {
JSONObject element = gb.getJSONObject(j);
int id = element.getInt("id");
int phone = element.getInt("phone");
String nom = element.getString("nom");
String email = element.getString("email");
String img = element.getString("img");
}
Upvotes: 1