1

There is some issue with the JSONObjectRequest in Volley library to receive the JSON data. I suppose I am going wrong somewhere in receiving the JSON object in the Java code. Following is my JSON output coming as a response from the php file hosted on server:

{"workers":[
           {"id":"1","name":"Raja","phonenumber":"66589952","occupation":"Plumber","location":"Salunke Vihar","rating":"4","Review":"Hard Worker","price":"80"},
           {"id":"2","name":"Aman","phonenumber":"789456","occupation":"Plumber","location":"Wakad","rating":"4","Review":"Good","price":"80"}
          ],
"success":1}

Following is clode from the Java file where I am using the JSON request using Volley library:

JsonObjectRequest jsonRequest = new JsonObjectRequest (Request.Method.POST, url,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try {
                        // I should receive the success value 1 here
                        int success = response.getInt("success");
                        //and should receive the workers array here
                        Log.d("response",response.getJSONArray("workers").toString());
                        Log.d("success",""+success);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_LONG).show();
                    recyclerView = (RecyclerView) findViewById(R.id.recyclerView);

                    recyclerView.setHasFixedSize(true);
                    layoutManager = new LinearLayoutManager(getApplicationContext());
                    recyclerView.setLayoutManager(layoutManager);
                    //Finally initializing our adapter
                    adapter = new WorkerAdapter(listWorkers);
                    recyclerView.setAdapter(adapter);
                   //adapter is working fine
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                   Log.d("error",error.toString());
                    Toast.makeText(getApplicationContext(),error.toString(),Toast.LENGTH_LONG).show();
                }
            }){
        @Override
        protected Map<String,String> getParams(){
            Map<String,String> params = new HashMap<String, String>();
            params.put("tag", "get_list");
            params.put("service", service);
            return params;
        }

Running the above code it goes to the error listener and gives the output as org.json.JSONException: End of input at character 0 of. But if I use StringRequest in place of JsonObjectRequest and receive the JSON response as a string then I am able to receive the output as a String but I can't use it further. So, please let me know where I am going wrong in receiving the JSONdata and suggest me the changes in the code that I must do.

EDIT- I am adding the php file which is returning the JSON object. Please let me know if there is some error over here:

<?php
error_reporting(0);
include("config.php");

if($_SERVER['REQUEST_METHOD']=='POST'){    
$tag = $_POST['tag'];
// array for JSON response
$response = array();

if ($tag == 'get_list') {
// Request type is check Login
$service = $_POST['service'];

//echo json_encode($service);   

// get all items from myorder table
$result = mysql_query("SELECT * FROM Workers WHERE Occupation = '$service'") or die(mysql_error());

if (mysql_num_rows($result) > 0) {

    $response["workers"] = array();

    while ($row = mysql_fetch_array($result)) {
            // temp user array
            $item = array();
            $item["id"] = $row["wID"];
            $item["pic"] = $row["Pic"];
            $item["name"] = $row["Name"];
            $item["phonenumber"] = $row["Phone Number"];
            $item["occupation"] = $row["Occupation"];
            $item["location"] = $row["Location"];
            $item["rating"] = $row["Rating"];
            $item["Review"] = $row["Review"];
            $item["price"] = $row["Price"];


            // push ordered items into response array
            array_push($response["workers"], $item);
           }
      // success
     $response["success"] = 1;
}
else {
    // order is empty
      $response["success"] = 0;
      $response["message"] = "No Items Found";
}
}   
echo json_encode($response);    
}
?>
Ankul Jain
  • 35
  • 1
  • 9
  • 2
    On the right side in the "Related" column, I see 10 questions with the exact same title. Have you read them? – RvdK Jun 30 '16 at 06:05
  • I think you are not receiving the response same as you added in the question try printing you response at very first line below `try { `.. You will get the problem..!! – Janki Gadhiya Jun 30 '16 at 06:09
  • @Rvdk Thanks for the suggestion. I have seen all those questions, all they have to say is that error is due to empty response. But, I m not receiving an empty response when I use `StringRequest`. It's just that I am receiving this error when I use `JsonObjectRequest`. So, please let me know if you have any other suggestions. – Ankul Jain Jun 30 '16 at 06:20
  • Can you put the output that you receive when making a stringrequest? – silverFoxA Jun 30 '16 at 06:35
  • @silverFoxA The output of the stringrequest is the JSON output I have mentioned above. It is coming like a string, I have indented it before posting here. Please let me know if you have any further suggestions – Ankul Jain Jun 30 '16 at 06:52
  • In that case I believe you have figured the error here the indents are coming before the string is causing JSON malfunction. Use JSON leniency – silverFoxA Jun 30 '16 at 06:54
  • @jankigadhiya I tried printing the response on the first line. But still the same error. I guess it is not reaching there and instead going to the ErrorListener. Please let me know if you have any other suggestions – Ankul Jain Jun 30 '16 at 07:16
  • print the error in `ErrorListner`..!! – Janki Gadhiya Jun 30 '16 at 07:28
  • @silverFoxA Do you want to say that the JSON output should itself come indented and not as a single line as in the string?? Please can you also have a look at the php file (which is sending the response) that I have added above. Let me know if there is some error over there. – Ankul Jain Jun 30 '16 at 07:36
  • @jankigadhiya `org.json.JSONException: End of input at character 0 of` is the error that I am getting hen using `JsonObjectRequest` and when I use the `StringRequest` then it prints the JSON reponse that you can find above – Ankul Jain Jun 30 '16 at 07:39
  • Then i suggest you to use `StringRequest`.. Update the code in question with `StringRequest` and state the problem you are facing while using `StringRequest`..!! – Janki Gadhiya Jun 30 '16 at 07:42
  • @AnkulJain what I meant is that if there is space as a prefix to your string it will throw JSON malformed exception – silverFoxA Jun 30 '16 at 07:47
  • @silverFoxA I guess there is no space as a prefix in the Json string received from the server. So, that might not be an error – Ankul Jain Jun 30 '16 at 14:03
  • Can you please share the endpoint url?! – silverFoxA Jun 30 '16 at 14:04
  • @silverFoxA The url of the server where the php file is placed is vorkal.com/read_data.php. Please suggest me the changes required. – Ankul Jain Jun 30 '16 at 15:41
  • @AnkulJain check my answe – silverFoxA Jun 30 '16 at 16:44

3 Answers3

0

Can you check that server is returning you a JSONObject and not the string? In Volley if the type of response is different then it will return the error.

Rajat Gupta
  • 127
  • 7
  • How can we check that server is returning a JSONObject or not?? I have also added the php file code on the server. Please let me know if you see that there are some changes required in the php file or the java file – Ankul Jain Jun 30 '16 at 07:13
  • While encoding response into JSON you have to use this method json_encode($response, JSON_FORCE_OBJECT) otherwise the json_encode returns a jsonArray and that might be the reason of your error – Rajat Gupta Jun 30 '16 at 09:14
0

you can use Gson to convert json string to object

 Gson gson = new Gson();
 GetWorkersResponse getWorkersResponse =gson.fromJson(response,GetWorkersResponse.class);


 class GetWorkersResponse {
          public boolean success;
          public List<Worker> workers = new ArryList<>(); 
     }

It's work for me.

Jugg
  • 1
0

When I ran the api end point I have got the following result instead of the one that you have been telling so. So stop giving irrelevant data.

"Plumber"{"workers":[{"id":"1","pic":"ttp:\/\/vorkal.com\/images\/vorkal_cover.PNG","name":"Raja","phonenumber":"66589952","occupation":"Plumber","location":"Salunke Vihar","rating":"4","Review":"Hard Worker. Very Professional.","price":"80"},{"id":"2","pic":"http:\/\/vorkal.com\/images\/vorkal_cover.PNG","name":"Aman","phonenumber":"789456","occupation":"Plumber","location":"Wakad","rating":"4","Review":"Good","price":"80"}],"success":1}

Where Plumber is not the tag at all, hence throws error as the same is not valid json string. There's error in your server side scripting. I request you to send the complete script without modification.

If you are not getting the JSONObject that means the following is a malformed json. Thus you can try the following code in server side

 function utf8ize($d) {
if (is_array($d)) {
    foreach ($d as $k => $v) {
        $d[$k] = $this->utf8ize($v);
    }
} else if (is_string ($d)) {
    return utf8_encode($d);
}
return $d;
}

where$d is the string/response. use it as echo json_encode($this->utf8ize($detail));

Also try the following in client side code

Gson gson = new Gson();
JsonReader reader = new JsonReader(new StringReader(result1));
reader.setLenient(true);

You may refer the solution to this question here click here

Community
  • 1
  • 1
silverFoxA
  • 4,549
  • 7
  • 33
  • 73
  • Thanks @silverFoxA for finding the error in server side scripting. I managed to get JSON from string using following code: `JSONObject jsonObject=new JSONObject(response); int success = jsonObject.getInt("success"); String workerArray=jsonObject.getString("workers"); JSONArray jar=new JSONArray(workerArray); JSONObject json = jar.getJSONObject(0);` – Ankul Jain Jul 01 '16 at 12:52