How to properly get JSONArray Items? - php

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

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

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.

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

Related

Why is this db query returning null instead of a JSONObject?

I have a PHP class that retrieves data from a Database and encodes it as a JSONArray to use it later in an Android app. For some reason is returning null and I have no clue what is wrong with it.
Here is the 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
if(isset($_GET['TAG_ID'])){
$id = $_GET['TAG_ID'];
$query = "SELECT *FROM lost_pets WHERE id = '$id'";
$result = $dbh->prepare($query);
$result->execute();
if ($result->fetchAll() > 0) {
foreach($dbh->query($query) as $row){
$pet["name"] = $row['name'];
$pet["breed"] = $row['breed'];
$pet["type"] = $row['type'];
$pet["description"] = $row['description'];
$pet["pictures"] = $row['pictures'];
$pet["location"] = $row['location'];
$pet["locality"] = $row['locality'];
$pet["userid"] = $row['userid'];
echo json_encode($result->fetchAll(PDO::FETCH_ASSOC));
}
}
}
?>
Android side:
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;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
is.close();
json = sb.toString();
elements = new JSONArray(json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
return elements;
}
The id is given by the app and I already checked that are possible values.I have a poor understanding of PHP, so probably is not a difficult problem to solve, anyway i hope you can help me with this, thank you!
I don't know what really happened here, but deleting that if clause solved the problem. Thanks for all your comments

Returning multiple JSON from php to android using volley

I have two tables
UserName Name
user01 name01
user02 name02
my second table
Name Subject
name01 math
name01 english
My php:
if($_SERVER['REQUEST_METHOD']=='GET'){
$id = $_GET['UserName'];
require_once('connect.php');
$sql = "SELECT * FROM mytable WHERE UserName='".$id."'";
$r = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($r)){
array_push($result,array(
'UserName'=>$row[0],
'name'=>$row[1],
)
);
$sqll= "SELECT * FROM subjecttable WHERE UserName='".$id."'";
$r = mysqli_query($con,$sql);
}
echo json_encode(array("result"=>$result));
mysqli_close($con);
}
echo json_encode(array("result" => $result));
now I have to receive the json inside while loop as well as the json outside the loop… right now I can receive the json outside while loop
my android code for retrieving the json outside the while loop
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(config.JSON_ARRAY);
for (int x = 0; x < result.length(); x++) {
JSONObject collegeData = result.getJSONObject(x);
username = collegeData.getString(config.KEY_UserName);
name = collegeData.getString(config.KEY_NAME);
}
} catch (JSONException e) {
e.printStackTrace();
}
Inside that while loop it will return the subjects in my second table and I should retrieve all of them…
Well...I did receive the multiple jsons but combining them both
{
"result":[
{"date":"01-01-2016",
"day_name":"Friday"},{"date":"02-01-2016",
"day_name":"Saturday"},{"date":"03-01-2016",
"day_name":"Sunday"},{"date":"04-01-2016",
"day_name":"Monday"},{"date":"05-01-2016",
"day_name":"Tuesday"},{"date":"06-01-2016",
"day_name":"Wednesday"},{"date":"07-01-2016",
"day_name":"Thursday"},
{MY OTHER JSON EXAMPLE--->"monday":"9",
"tuesday":"9" }]}
Then i used two for loops inside onresponse
First for loop was 0 to result.length-1...That wont include the last array
Then the second for was from result.length-1 to result.length.
With this implementation i was able to take different jsons when a single onResponse
NOTE The second json should not be a repeating set.
private void showJSON(String response){
try {
JSONObject jsonObject =new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(config.JSON_ARRAY);
for(int x=0;x<result.length()-1;x++) {
JSONObject collegeData = result.getJSONObject(x);
//collecting present object in json
ClassList.add(new totalClassObject(collegeData.getString("date"),collegeData.getString("day_name")));
RefreshListVIew();
}
for(int x=result.length()-1;x<result.length();x++) {
JSONObject collegeDays = result.getJSONObject(x);
//For Fetching Second type json
}
} catch (JSONException e) {
e.printStackTrace();
}
}

Android - JSONException parsing data

My "nhanvien" table has 3 columns : "id", "Maso", "Hoten". I use the code below to get all data from this table but I've got an error.
<?php
// get all nhanvien from nhanvien table
$response = array();
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
$result = mysql_query("SELECT *FROM nhanvien") or die(mysql_error());
// looping through all results
// nhanvien node
if (mysql_num_rows($result) > 0) {
$response["nhanvien"] = array();
while ($row = mysql_fetch_array($result)) {
$nhanvien = array();
$nhanvien ["id"] = $row["id"];
$nhanvien ["Maso"] = $row["Maso"];
$nhanvien ["Hoten"] = $row["Hoten"];
array_push($response["nhanvien"], $nhanvien);
}
$response["success"] = 1;
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No nhanvien found";
echo json_encode($response);
?>
I have this error :
Error parsing data org.json.JSONException: Value Connected of type java.lang.String cannot be converted to JSONObject
Here is my android code:
try {
URL murl = new URL(url);
URLConnection urlConnection = murl.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(),"UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
reader.close();
json = sb.toString();
Log.d("connect...", json.toString());
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(new String(json));
Log.d("parse...", jObj.toString());
} catch (JSONException e) {
Log.e("JSON Parser 123", "Error parsing data " + e.toString());
//Log.e("JSON Parser", "Error parsing data [" + e.getMessage()+"] "+json);
}
// return JSON String
return jObj;
}

JSONException: Value of type java.lang.String cannot be converted to JSONObject

I am facing a problem, a valid JSON string cannot become a JSON object.
I have tested the response coming from the server, it is a valid JSON.
I have checked on the internet, it is about the problem of UTF-8 with DOM. But even I changed the charset in Notepad++ into UTF-8 with no DOM, the same error still coming out.
My codes:
<?php
require_once("Connection/conn.php");
//parse JSON and get input
$json_string = $_POST['json'];
$json_associative_array = json_decode($json_string,true);
$userId = $json_associative_array["userId"];
$password = $json_associative_array["password"];
$userType = $json_associative_array["userType"];
//get the resources
$json_output_array = array();
$sql = "SELECT * FROM account WHERE userId = '$userId' AND password = '$password' AND userType = '$userType'";
$result = mysql_query($sql);
//access success?
if (!$result) {
die('Invalid query: ' . mysql_error());
$json_output_array["status"] = "query failed";
}
else{
$json_output_array["status"] = "query success";
}
//find the particular user?
if (mysql_num_rows($result) > 0){
$json_output_array["valid"] = "yes";
}
else{
$json_output_array["valid"] = "no";
}
//output JSON
echo json_encode($json_output_array);
?>
Android codes:
public boolean login() {
// instantiates httpclient to make request
DefaultHttpClient httpClient = new DefaultHttpClient();
// url with the post data
String url = SERVER_IP + "/gc/login.php";
JSONObject holder = new JSONObject();
try {
holder.put("userId", "S1");
holder.put("password", "s12345");
holder.put("userType", "supervisor");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Log.d("JSON", holder.toString());
// HttpPost
HttpPost httpPost = new HttpPost(url);
//FormEntity
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("json", holder.toString()));
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// execution and response
boolean valid = false;
try {
HttpResponse response = httpClient.execute(httpPost);
Log.d("post request", "finished execueted");
String responseString = getHttpResponseContent(response);
Log.d("post result", responseString);
//parse JSON
JSONObject jsonComeBack = new JSONObject(responseString);
String validString = jsonComeBack.getString("valid");
valid = (validString.equals("yes"))?true:false;
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return valid;
}
private String getHttpResponseContent(HttpResponse response) {
String responseString = "";
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
responseString += line ;
}
rd.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return responseString;
}
JSON come from server:
{
"status": "query success",
"valid": "yes"
}
unformat JSON:
{"status":"query success","valid":"yes"}
When I copy this into notepad++, it becomes ?{"status":"query success","valid":"yes"}
It seems that there is a invisible character .
I fixed it with the solution provided by MuhammedPasha, which substring the JSON string to remove invisible character. And I substring the JSON String from 1 to fix my problem.
There is a way to detect those invisible characters, copy the log result into notepad++.(copy! no typing!) If there are any ?(question mark), they indicates that there are some invisible character.
I had a same problem. Maybe you need to save without unicode signature (BOM).

PHP SQL array json encode error when converting to java

I am echoing a json set of results back to android:
$result = mysql_query($query) or die(mysql_error());
$resultNo = mysql_num_rows($result);
// check for successful store
if ($result != null) {
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
return json_encode($rows);
} else {
return false;
}
}
But when I try to convert the string to a JSONObject at the other end i get:
11-13 22:18:41.990: E/JSON(5330): "[{\"email\":\"fish\"}]"
11-13 22:18:41.990: E/JSON Parser(5330): Error parsing data org.json.JSONException: Value [{"email":"fish"}] of type java.lang.String cannot be converted to JSONObject
I have tried this with a larger result set and thought that it would be something to do with null values however trying it as above with just one value still returns an error.
Any help greatly appreciated
EDIT:
Android methods...
public JSONObject searchPeople(String tower) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", search_tag));
params.add(new BasicNameValuePair("tower", tower));
// getting JSON Object
JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);
// return json
return json;
}
JSON Parser class...
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.e("JSON", 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());
}
// return JSON String
return jObj;
}
As #MikeBrant mentioned above, you need to pass through JSONArray first.
Replace this:
//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());
}
With this:
// try parse the string to a JSON object
try {
JSONArray jArray = new JSONArray(json);
for(i=0; i < jArray.length(); i++) {
JSONObject jObj = jArray.getJSONObject(i);
Log.i("jObj", "" + jObj.toString());
// Parsing example
String email = jObj.getString("email");
Log.i("email", email);
}
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
PHP w/ str_replace:
$result = mysql_query($query) or die(mysql_error());
$resultNo = mysql_num_rows($result);
// check for successful store
if ($result != null) {
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
$json_string = json_encode($rows);
$json_string = str_replace("\\", "", $json_string, $i);
return $json_string;
} else {
return false;
}
}
$result = mysql_query($query) or die(mysql_error());
$resultNo = mysql_num_rows($result);
// check for successful store
if ($result != null) {
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
return json_encode($rows);
} else {
return false;
}
I think it's just your braces
What you are passing to JSONObject is in fact an array with a single object in it.
JSONObjectis expecting the syntax to be only representative of a single object containing key-value pairs (i.e. properties).
You need to not pass an array for this to work, or you need to use JSONArray to decode the JSON.
I had similar problem when I needed to pass json data from php to java app, this solved my problem:
$serialliazedParams = addslashes(json_encode($parameters));
You need to escape certain characters added by PHP, as well as substring your json string to cut out the additional characters at the front of the returned string.
One way to do it is like so:
ANDROID/JAVA code
JSONObject response = new JSONObject(responseString.substring(responseString.indexOf('{'),responseString.indexOf('}') +1).replace("\\",""));
You should do it a bit more neatly, but the point is that you have to ensure that the string you're passing in has no hidden characters, and to replace the first """ character with nothing as it can cause the exception.

Categories