`I have a PHP code that 1st calculates if the image parameters retrieval from DB was successful or not and then inserts into response the 3 parameters (Id,name,url) for each image. Then it returns json format response. I am collecting that response in android in the form of String then I need to convert it to jsonArray. While conversion, I get exception.
PHP CODE:
<?php
//Importing dbdetails file
require_once 'dbDetails.php';
//connection to database
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect...');
//sql query to fetch all images
$sql = "SELECT * FROM MyImages";
//getting images
$result = mysqli_query($con,$sql);
//response array
$response = array();
$response['error'] = false;
$response['images'] = array();
//traversing through all the rows
while($row = mysqli_fetch_array($result)){
$temp = array();
$temp['id']=$row['id'];
$temp['name']=$row['name'];
$temp['url']=$row['url'];
array_push($response['images'],$temp);
}
//displaying the response
echo json_encode($response);
?>
result is the response from php code in the below code
android code:
@Override protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pd.isShowing()){
pd.dismiss();
}
txtJson.setText(result);
try {
JSONArray jsonArr = new JSONArray(result);
showGrid(jsonArr);
} catch (JSONException e) {
e.printStackTrace();
txtJson.setText("Exception in jsonArry");
}
}
Then how to do it properly?
The response string is->
{"error":false,"images":[{"id":"1","name":"1","url":"https:\/\/swulj.000webhostapp.com\/AndroidUploadImage\/uploads\/1.jpg"},{"id":"2","name":"2","url":"https:\/\/swulj.000webhostapp.com\/AndroidUploadImage\/uploads\/2.jpg"},{"id":"3","name":"3","url":"https:\/\/swulj.000webhostapp.com\/AndroidUploadImage\/uploads\/3.jpg"},{"id":"4","name":"ygff","url":"https:\/\/swulj.000webhostapp.com\/AndroidUploadImage\/uploads\/4.jpg"}]}
Is this in proper json format? What should I do?
CodePudding user response:
Your android code should be like this
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pd.isShowing()){
pd.dismiss();
}
txtJson.setText(result);
try {
JSONObject jsonObj = new JSONObject(result);
showGrid(jsonObj.optJsonArray("images"));
} catch (JSONException e) {
e.printStackTrace();
txtJson.setText("Exception in jsonArry");
}
}
CodePudding user response:
As the string response is not surrounded by "[" and "]", I surrounded it and no exception occurs.
CODE:
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pd.isShowing()){
pd.dismiss();
}
txtJson.setText(result);
try {
String res = "[" result "]";
JSONArray jsonArr = new JSONArray(res);
showGrid(jsonArr);
/*JSONObject jsonObj = new JSONObject(result);
showGrid(jsonObj.optJsonArray("images"));*/
} catch (Exception e) {
e.printStackTrace();
txtJson.setText("Exception in jsonArry");
}
}