org.json.JSONException: No value for status - java

org.json.JSONException: No value for status
Here is my java code method for json parse
java
public void performSearch() {
String url= "http://192.168.0.136/fyp/stitle1.php";
RequestQueue requestQueue = Volley.newRequestQueue(Stitle.this);
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST,url,null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Response", response.toString());
try {
//converting the string to json array object
JSONObject array = new JSONObject();
//Log.i("test", " value : " + array.getString("status"));
Log.i("test", " value : " + response.getString("status"));
if (array.getString("status").equals("true")) {
JSONArray jsonArray = array.getJSONArray("search");
Log.i("test", " value : " + array);
for (int i = 0; i < jsonArray.length(); i++) {
//getting product object from json array
JSONObject product = jsonArray.getJSONObject(i);
//adding the product to product list
boolean add = productList.add(new list(
product.getLong("isbn"),
product.getString("title"),
product.getString("authors"),
product.getInt("accession"),
product.getString("publisher"),
product.getInt("pubyear"),
product.getInt("pages"),
product.getInt("rak"),
product.getInt("hr"),
product.getInt("vr"),
product.getLong("barcode")
));
}
} else {
Log.i("test", "else error");
}
} catch (JSONException e) {
e.printStackTrace();
Log.i("test", e.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "error:" + error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Title", searchtitle.getText().toString());
return params;
}
};
requestQueue = Volley.newRequestQueue(Stitle.this);
requestQueue.add(jsObjRequest);
}
Php file to pass parameter to android jsonobject
stitle1.php
php
<?php
// array for JSON response
$response = array();
//set values just in case any thing goes wrong
$response["status"] = 0;
$response["message"] = "Error before start";
// check for post data with isset
if (isset($_POST["Title"])) {
$title = $_POST["Title"];
// You were not using PDO so I dumped your connection and require you to provide...
//...a configuration file for ...
require_once 'connection.php';
// ...these variables
$host = 'localhost';
$db = 'fyp';
$user = 'root';
$pass = '';
$charset = 'utf8';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try{
// connecting to db with PDO
$pdo = new PDO($dsn, $user, $pass, $opt);
$sql = 'SELECT isbn, title, authors, accession, publisher, pubyear, pages, rak, hr, vr, barcode
FROM books
WHERE title LIKE :titleParam';
$titleParam = "%".$title."%";
$stmt = $pdo->prepare($sql);
// Bind the parameter
$stmt->bindParam(':titleParam', $titleParam, PDO::PARAM_STR);
$res = $stmt->execute();
if ($res) {
// success
$response["status"] = 1;
// connection node
$response["books"] = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$data = array();
$data["isbn"] = $row["isbn"];
$data["title"] = $row["title"];
$data["authors"] = $row["authors"];
$data["accession"] = $row["accession"];
$data["publisher"] = $row["publisher"];
$data["pubyear"] = $row["pubyear"];
$data["pages"] = $row["pages"];
$data["rak"] = $row["rak"];
$data["hr"] = $row["hr"];
$data["vr"] = $row["vr"];
$data["barcode"] = $row["barcode"];
array_push($response["books"], $data);
}
}
else {
// required field is missing
$response["status"] = 2;
$response["message"] = "No data returned";
}
}
catch (Exception $e){
$response["status"] = 3;
$response["message"] = "Error occurred." . $e->getMessage();
}
}
else {
$response["status"] = 4;
$response["message"] = "Post parameters are not correct";
}
// echoing JSON response
echo json_encode($response);
?>
When I run my application these lines appear on logcat panel
I/test: value : 4
I/test: org.json.JSONException: No value for status
These are two lines appear on logcat which indicate error about that the parameter was not sent properly

We will take this step for step. Lets start with response.
Your PHP code is returning a status value =4 which indicates that you are not getting the parameters sent to the PHP code properly. It is possible that getParams() is not even being called.
Change the getParams() method to look like this:
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
try{
String s = searchtitle.getText().toString();
Log.e("Volley request", "getParams called : " + s);
params.put("Title", s);
}
catch(Exception ex){
Log.e("Volley request ERROR", ex.getMessage());
}
return params;
}
For the second part, lets try to deal with the parsing code. Change the code to look like this:
Now regardless of how your php code responds, you will be getting a well formed JSONObject as a response which you can parse and react to it appropriately.
Change the onResponse() part of the code to look like this:
#Override
public void onResponse(JSONObject response) {
// Log.d("Response", response.toString());
try {
//converting the string to json array object
if(response != null){
if(!response.has("status"){
Log.e(TAG, "Something went wrong -- no status key!");
return;
}
else{
int status = response.optInt("status", -1);
if(status == 1){
//There could be quite a few books in this response...
//...you might want to parse in an AsyncTask instead
parseJsonObject(response);
}
else{
String message = response.optString("message", "uups");
Log.e(TAG, "error message = " + message);
return;
}
}
}
}
catch(Exception ex){
Log.e(TAG, ex.getMessage());
}
}
And now to parse the JSONObject:
Map<String, String> booksMap = new HashMap<>();
private void parseJsonObject(JSONObject jsonObject){
try{
if(jsonObject == null) return;
//Not Available!
String na = "NA"
Log.i("test", " value : " + jsonObject.toString());
if(jsonObject.has("books")){
JSONArray array = jsonObject.getJSONArray("books");
for(int i = 0; array.length(); i++){
JSONObject book = array.getJSONObject(i);
Iterator<String> it = book.keys();
while(it.hasNext()){
String key = it.next();
String value = book.optString(key, na);
booksMap.put(key, value);
}
}
}
}
catch(Exception ex){
Log.e(TAG, ex.getMessage());
}
}

Related

How to fetch sum of column in MySQL using PHP based on id and display it in Android using Volley

I have a table called hotel_review in this I have hotel_stars column and I want to display the sum of all the hotel stars in Android using Volley. I want to display the average of the hotel rating, to do this I need the sum of the column. I think I'm close but not getting the values. I'm not getting any error but I can not fetch the values as well.
my php code:
<?php
require "init.php";
header('Content-Type: application/json;charset:UTF-8');
$hotel_id = $_POST['hotel_id'];
$query = mysqli_query($con, "SELECT SUM(hotel_stars) AS 'Total' FROM hotel_review WHERE hotel_id = '".$hotel_id."';");
$row = mysqli_fetch_assoc($query);
$sum = $row['Total'];
if($query)
{
$code = "getvalue";
$data[]['Total'] = $sum;
$result = array("code"=>$code,"stars" => $data);
echo json_encode($result);
}else {
$code = "not_get";
$msg = "Try Again....";
array_push($response, array("code"=>$code,"msg"=>$msg));
//echo("Error description: " . mysqli_error($con));
header('Content-Type: application/json;charset:UTF-8');
echo json_encode($response);
// echo("Error description: " . mysqli_error($con));
}
mysqli_close($con);
?>
my android code:
public void getHotelStars()
{
StringRequest stringRequest = new StringRequest(Request.Method.POST, getStars,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("response", response);
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);
String code = jsonObject.getString("code");
if (code.equals("not_get")) {
Toast.makeText(hotel_reviews.this, "error", Toast.LENGTH_SHORT).show();
} else {
String totalStars = jsonObject.getString("stars");
// String totalCount = jsonObject.getString("total_stars");
Toast.makeText(hotel_reviews.this, ""+totalStars, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(hotel_reviews.this, "error", Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("hotel_id",HotelId);
//params.put("division",EmployeeDivision);
return params;
}
};MySingleton.getInstance(hotel_reviews.this).addToRequestque(stringRequest);
}
Im getting the proper hotel_id in params.put so no error is there in fetching id.
use it like this after you fire your query:
while ($row = mysqli_fetch_assoc($query)) {
$sum=$row["Total"];
echo $sum;
}
after your query and see if your total is there in $sum. Thereafter you can start using that anywhere.

volley.parsererror:org.json.JSONException: value br of type java.lang.string cannot be converted to JSONObject

volley.parsererror:org.json
value br of type java.lang.string cannot be converted to JSONObject
Android Code
public void performSearch() {
String url= "http://192.168.0.136/fyp/stitle.php";
RequestQueue requestQueue = Volley.newRequestQueue(Stitle.this);
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST,url,null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i("Response", response.toString());
try {
//converting the string to json array object
JSONObject array = new JSONObject();
Log.i("test", " value : " + array.getString("status"));
if (array.getString("status").equals("true")) {
JSONArray jsonArray = array.getJSONArray("search");
Log.i("test", " value : " + array);
for (int i = 0; i < jsonArray.length(); i++) {
//getting product object from json array
JSONObject product = jsonArray.getJSONObject(i);
//adding the product to product list
boolean add = productList.add(new list(
product.getLong("isbn"),
product.getString("title"),
product.getString("authors"),
product.getInt("accession"),
product.getString("publisher"),
product.getInt("pubyear"),
product.getInt("pages"),
product.getInt("rak"),
product.getInt("hr"),
product.getInt("vr"),
product.getLong("barcode")
));
}
} else {
Log.i("test", "else error");
}
} catch (JSONException e) {
e.printStackTrace();
Log.i("test", e.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "error:" + error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Title", searchtitle.getText().toString());
return params;
}
};
requestQueue = Volley.newRequestQueue(Stitle.this);
requestQueue.add(jsObjRequest);
}
}
Php Code file to send json to android java file
<?php
include"connection.php";
if (isset($title = $_POST["Title"]){
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$query =$conn->prepare('SELECT isbn, title, authors, accession, publisher, pubyear, pages, rak, hr, vr, barcode FROM books where title like "%'.$title.'%" ');
$query->execute();
$query->bind_result($isbn, $title, $authors, $accession, $publisher, $pubyear, $pages, $rak, $hr, $vr, $barcode);
$books = array();
$data =array();
//traversing through all the result
while($query->fetch()){
$temp = array();
$temp['isbn'] = $isbn;
$temp['title'] = $title;
$temp['authors'] = $authors;
$temp['accession'] = $accession;
$temp['publisher'] = $publisher;
$temp['pubyear'] = $pubyear;
$temp['pages'] = $pages;
$temp['rak'] = $rak;
$temp['hr'] = $hr;
$temp['vr'] = $vr;
$temp['barcode'] = $barcode;
array_push($data, $temp);
}
$books['status'] = true;
$books['search'] = $data;
//displaying the result in json format
echo json_encode($books);
}}
?>
When run applicaion this error toast on screen [volley.parsererror:org.json.JSONException: value br of type java.lang.string cannot be converted to JSONArray]
There are several issues with your code. Let us deal with your PHP, first. Your PHP code should be designed to return some useful information whether it is successful or it fails--and why it fails.
I can't tell which class you are using to access your MySQL data, but in any case it is not PDO. I will show you an example using PDO because you can use prepared statements, which will help protect you from SQL injections attacks.
your PHP code is poorly designed and in addition to that it is open to a SQL injection attack!
Begin your PHP code with a isset check of your parameters. This code will return a JSONObject regardless of whether your query fails or not. This makes it easier to see what is going wrong--when it goes wrong.
<?php
// array for JSON response
$response = array();
//set values just in case any thing goes wrong
$response["status"] = 0;
$response["message"] = "Error before start";
// check for post data with isset
if (isset($_POST["Title"])) {
$title = $_POST["Title"];
// You were not using PDO so I dumped your connection and require you to provide...
//...a configuration file for ...
require_once __DIR__ . '/db_config.php';
// ...these variables
$host = DB_SERVER;
$db = DB_DATABASE;
$user = DB_USER;
$pass = DB_PASSWORD;
$charset = 'utf8';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try{
// connecting to db with PDO
$pdo = new PDO($dsn, $user, $pass, $opt);
$sql = 'SELECT isbn, title, authors, accession, publisher, pubyear, pages, rak, hr, vr, barcode
FROM books
WHERE title LIKE :titleParam';
$titleParam = "%".$title."%";
$stmt = $pdo->prepare($sql);
// Bind the parameter
$stmt->bindParam(':titleParam', $titleParam, PDO::PARAM_STR);
$res = $stmt->execute();
if ($res) {
// success
$response["status"] = 1;
// connection node
$response["books"] = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$data = array();
$data["isbn"] = $row["isbn"];
$data["title"] = $row["title"];
$data["authors"] = $row["authors"];
$data["accession"] = $row["accession"];
$data["publisher"] = $row["publisher"];
$data["pubyear"] = $row["pubyear"];
$data["pages"] = $row["pages"];
$data["rak"] = $row["rak"];
$data["hr"] = $row["hr"];
$data["vr"] = $row["vr"];
$data["barcode"] = $row["barcode"];
array_push($response["books"], $data);
}
}
else {
// required field is missing
$response["status"] = 2;
$response["message"] = "No data returned";
}
}
catch (Exception $e){
$response["status"] = 3;
$response["message"] = "Error occurred." . $e->getMessage();
}
}
else {
$response["status"] = 4;
$response["message"] = "Post parameters are not correct";
}
// echoing JSON response
echo json_encode($response);
?>

Receive & Output JSON Error Message Android

I have created an API for the purpose to retrieve data from database. Now I able to retrieve status, message and data from the API no matter I input the credentials correct or incorrect. There are two version of output. I used POSTMan to test on and that it seems working but when I try on Android, success message is okay but not the error one.
#POST
#Path("/appdatas")
public Response getSAppData(AppDataRequest adr) {
Response data = ads.getSAppData(adr.getId(), adr.getEmail(), adr.getPassword());
return data;
}
#SuppressWarnings("unchecked")
public Response getSAppData(int id, String email, String password){
Map<String, AppData> AppDataHM = new HashMap<String, AppData>();
Map<String, Data> DataHM1 = new HashMap<String, Data>();
Map<String, List<String>> DataHM2 = new HashMap<String, List<String>>();
Map ADHMDHM = new HashMap<>();
Data data = DataHM.get(new AppDataRequest (id, email, password));
List<String> message = new ArrayList<>();
List<String> data2 = new ArrayList<>();
if(data != null){
message.add("");
AppDataHM.put("AppData", new AppData("success", message));
DataHM1.put("Data", data);
ADHMDHM.putAll(AppDataHM);
ADHMDHM.putAll(DataHM1);
String ADHMDHM1 = new Gson().toJson(ADHMDHM);
return Response.status(200).entity(ADHMDHM1).build();
}
else{
message.add("Your login information is invalid. Please try with the correct information");
AppDataHM.put("AppData", new AppData("error", message));
DataHM2.put("Data", data2);
ADHMDHM.putAll(AppDataHM);
ADHMDHM.putAll(DataHM2);
String ADHMDHM2 = new Gson().toJson(ADHMDHM);
return Response.status(500).entity(ADHMDHM2).build();
}
}
When I use POSTMan, I able to retrieve both output.
{
"AppData": {
"status": "success",
"message": [
""
]
},
"Data": {
"token": "token1"
}
}
{
"AppData": {
"status": "error",
"message": [
"Your login information is invalid. Please try with the correct information"
]
},
"Data": []
}
When I apply the following code on Android, I able to retrieve data for success one but not the error one.
private void makeJsonObjectRequest(){
showpDialog();
String id1 = mEditTextID.getText().toString();
String email1 = mEditTextEmail.getText().toString().trim();
String password1 = mEditTextPassword.getText().toString();
HashMap<String, String> params = new HashMap<String, String>();
params.put("id", id1);
params.put("email", email1);
params.put("password", password1);
JsonObjectRequest request = new JsonObjectRequest(url, new JSONObject(params), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject AppData = response.getJSONObject("AppData");
String status = AppData.getString("status");
String message = AppData.getString("message");
//JSONObject Data = response.getJSONObject("Data");
//String token = Data.getString("token");
jsonResponse = "";
jsonResponse += "Status: " + status + "\n";
jsonResponse += "\n";
jsonResponse += "Message: " + message + "\n";
//jsonResponse += "\n";
//jsonResponse += "Token: " + token + "\n";
mTextViewMain.setText(jsonResponse);
hidepDialog();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(),
"Error: " + e.getMessage(),
Toast.LENGTH_SHORT).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error1: " + error.getMessage());
Toast.makeText(getActivity(),
"Error2: " + error.getMessage(), Toast.LENGTH_SHORT).show();
hidepDialog();
}
});
AppController.getInstance().addToRequestQueue(request);
}
How possible I can get the output as shown in the 'error' output and display in the TextView?
Thanks for everyone for viewing this question.
Why are you returning status 500 in your script? Volley assumes code 500 as error
return Response.status(500).entity(ADHMDHM2).build();
Try changing it to 200 and check
You can use this link to generate concrete classes for the json. Once you have the concrete classes then you can use GSON to convert json text to class. This way you will have concrete json to class mapping.
May be this can help.
For Message try this:
JSONArray messageArray = AppData.getJSONArray("message");
String message = messageArray.toString();

How can I pass parameters to PHP files correctly

I have problem sending a string parameter to a PHP file to download a song inserting the song's name from a edit text. I don't understand the error I'm receiving.
Thanks in advance for the help!
LOGCAT:
Response from url: {"error":false,"message":"Musics fetched successfully.","musics":[]}
i don't know why the array is empty.
The PHP file works if i use a rest client passing the song's name but not in the URL.
This is my code:
ANDROID SIDE:
class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//Toast.makeText(MainActivity.this, "Json Data is downloading", Toast.LENGTH_LONG).show();
canzone = editText.getText().toString();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "http://blabla.org/AndroidMusicDownload/downloads/getMusic.php?canzone=" + canzone;
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
/* title=jsonObj.getString("title");
link=jsonObj.getString("link");
HashMap<String, String> contact = new HashMap<>();
contact.put("title", title);
contact.put("link", link);
System.out.println("LINK: "+link);
contactList.add(contact);
*/
Toast.makeText(MainActivity.this, jsonObj.getString("message"), Toast.LENGTH_SHORT).show();
JSONArray jsonArray = jsonObj.getJSONArray("musics");
for (int i = 0; i < jsonArray.length(); i++) {
//Declaring a json object corresponding to every pdf object in our json Array
JSONObject jsonObject = jsonArray.getJSONObject(i);
//Declaring a Pdf object to add it to the ArrayList pdfList
// Pdf pdf = new Pdf();
// String pdfName = jsonObject.getString("name");
//String pdfUrl = jsonObject.getString("url");
//pdf.setName(pdfName);
//pdf.setUrl(pdfUrl);
//pdfList.add(pdf);
canzone_cantante = jsonObject.getString("canzone_cantante");
}
/* pdfAdapter=new PdfAdapter(MainActivity.this,R.layout.list_layout, pdfList);
listView.setAdapter(pdfAdapter);
pdfAdapter.notifyDataSetChanged();*/
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("canzone_cantante", canzone_cantante);
//contact.put("email", email);
// contact.put("mobile", mobile);
/* Toast.makeText(getApplicationContext(),
"LINK: "+link ,
Toast.LENGTH_LONG).show();*/
// adding contact to contact list
System.out.println("LINK: " + canzone_cantante);
contactList.add(contact);
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
PHP CODE:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$canzone = $_POST['canzone'];
require_once 'dbDetails.php';
$con = mysqli_connect(DB_HOST,DB_USERNAME,DB_PASSWORD,DB_NAME) or die("Unable to connect");
$sql = "SELECT * FROM music where canzone = '$canzone'";
$result = mysqli_query($con,$sql);
//response array
$response = array();
$response['error'] = false;
$response['message'] = "Musics fetched successfully.";
$response['musics'] = array();
//traversing through all the rows
while($row =mysqli_fetch_array($result)){
$temp = array();
$temp['id'] = $row['id'];
$temp['canzone'] = $row['canzone'];
$temp['canzone_cantante'] = $row['canzone_cantante'];
$temp['url'] = $row['url'];
array_push($response['musics'],$temp);
}
echo json_encode($response);
}
You are sending your canzone parameter with get request( inAndroid) but trying to get it by POST global variable(in php)
so i suggest changing your php from $canzone= $_POST['canzone']; to $canzone= $_GET['canzone'];
EDIT
also change the if statement here
if($_SERVER['REQUEST_METHOD']=='POST'){
to
if($_SERVER['REQUEST_METHOD']=='GET'){
You send song name as GET not like post.
Also you need to urlencode name of a song, if it has more then one word in name.
Cheers :)
As I understood you post the request like this from Android App
String url = "http://blabla.org/AndroidMusicDownload/downloads/getMusic.php?canzone=" + canzone;
But there is a problem that you send 'canzone' in URL, so this is GET parameter, and in the PHP you grab this variable from $_POST, just change $_POST to $_GET, should work
Try with replacing this line
$canzone = $_POST['canzone'];
with
$canzone = $_REQUEST['canzone'];

PHP Parse Error JSON Exception With Redundant Value - Failed To Fetch Datacom

I was in the middle of getting my data from my server (XAMPP), and I'm having a problem regarding with the return format (I believed). I was getting my data and put it in the cardView - recyclerView .
This is my php code: orgList.php
<?php
//if($_SERVER['REQUEST_METHOD'] == ''){
require('dbConnect.php');
$SQLi_ORG_FEEDS = "SELECT organizationName,organizationDescription,organizationCategory,
organizationCurrentMembers,organizationMaxMembersNo,organizationType FROM org_information";
$query = mysqli_query($dbConnect,$SQLi_ORG_FEEDS) or die("Error".mysqli_error($dbConnect));
$checkRow = mysqli_num_rows($query);
$response = array();
$response["success"] = "success";
if($checkRow > 0){
while ($getRecord = mysqli_fetch_array($query)) {
$response[] = $getRecord;
}
echo json_encode($response);
}
else {
$response['failed'] = 'failed';
echo json_encode($response);
}
//}
My java: orgFragment.java
public void parseJSONData(){
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
JsonArrayRequest jsonArray = new JsonArrayRequest(ServerScripts.PHP_SCRIPT_PATH + ServerScripts.PHP_GET_FEEDS, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if (response.length() > 0){
try {
organizationDataList.clear();
for (int i = 0; i < response.length(); i++ ){
JSONObject jsonObject = response.getJSONObject(i);
OrganizationData organizationData = new OrganizationData();
//SQL TABLE NAME
if (!jsonObject.isNull("organizationName")){
organizationData.orgName = jsonObject.getString("organizationName");
}
if (!jsonObject.isNull("organizationType")){
organizationData.orgType = jsonObject.getString("organizationType");
}
if (!jsonObject.isNull("organizationDescription")){
organizationData.orgDesc = jsonObject.getString("organizationDescription");
}
if (!jsonObject.isNull("organizationCategory")){
organizationData.orgCategory = jsonObject.getString("organizationCategory");
}
if (!jsonObject.isNull("organizationCurrentMembers")){
organizationData.orgCurrentMembers = jsonObject.getInt("organizationCurrentMembers");
}
if (!jsonObject.isNull("organizationMaxMembersNo")){
organizationData.orgMaxMembers = jsonObject.getInt("organizationMaxMembersNo");
}
//ADD
organizationDataList.add(organizationData);
}
//NOTIFY
orgListAdapter.notifyDataSetChanged();
}catch (Exception e){
e.printStackTrace();
Toast.makeText(getContext(),e.toString(),Toast.LENGTH_LONG).show();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
String getErrorMsg = error.toString();
Toast.makeText(getContext(),"Failed to Fetch Data" + getErrorMsg,Toast.LENGTH_LONG).show();
}
});
requestQueue.add(jsonArray);
}
I check my format in postman if returned in json. And I get this response. Can someone help me with this one, the PHP coding. Where do I get wrong in JSON format.
This is wrong:
echo json_encode($response);
}
else {
echo $response["failed"] = "failed";
^^^^^^^^
Your client is expecting json. If the else clause is executed, you script outputs failed, which is invalid/illegal json, which will cause a parse error. You probably wanted something more like
$response['failed'] = 'failed';
echo json_encode($response);
This is also wrong:
while ($getRecord = mysqli_fetch_array($query)) {
^-- one row of result data as an array
$response["organizationName"] = $getRecord;
^--stuff entire row array into response
You're also fetching MULTIPLE records from the db (otherwise, why else fetch in a loop), and continually assign the entire result row array into multiple fields of your response, then overrwrite those previous results with the next row. That means you'll only ever get the LAST record fetched from your query.
You want:
while ($getRecord = mysqli_fetch_array($query)) {
$response["organizationName"][] = $getRecord['organizationName'];
^-append to array
etc..
}
instead, or maybe just
while ($getRecord = mysqli_fetch_array($query)) {
$response[] = $getRecord;
}

Categories