0

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]

6
  • Log your result to the logcat so you can see the JSON response that is returned, then post a sample of the data. Commented May 27, 2018 at 22:23
  • You should be informed that your PHP code is open for SQL injection! You should also be checking your POST parameters with isset and thus give your PHP code an elegant exit if the parameter is not set properly. Commented May 27, 2018 at 22:28
  • No JSON response on logcat. Error toast on screen. @Barns Commented May 28, 2018 at 0:35
  • 1
    There are several issues with your code. Too many to cover in one question. But firstly, your PHP is not designed to return a JSONArray! It is designed to return a JSONObject. Secondly, your PHP code is poorly designed and in addition to that it is open to a SQL injection attack! You should be using a prepared statement any time you are using variables to filter your result set. You should be using isset for your POST parameters. You should return some type of well formed JSON response, when your PHP code fails for any reason. After that is fixed, we can get started on the Android code. Commented May 28, 2018 at 1:50
  • Hi @Barns.. Now I change my code to JSONObject and php to isset. But same error appear.. I'm poor in coding help Commented May 29, 2018 at 21:28

1 Answer 1

1

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);
?>
Sign up to request clarification or add additional context in comments.

7 Comments

this is appear on logcat > org.json.JSONException: No value for status
That is because you have this in your code JSONObject array = new JSONObject(); Log.i("test", " value : " + array.getString("status")); :: You are creating an new object array but nothing is in it! :: You need to write this: Log.i("test", " value : " + response.optInt("status", -1));
I/test: value : 4 I/test: org.json.JSONException: No value for status
Looks like the status value is "4" which according to the PHP code would mean, that the parameter was not sent properly.
Now how I send parameter properly
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.