1

I'm am using Volley to send an HTTP request in Android and I'm getting this error:

java.lang.String cannot be converted to JSONObject.

On the server side, I use a PHP script to get values from the database.

My Android code:

String server_url = "http://192.168.225.40/server/greetings.php";
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, server_url,null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {

                        try {
                            name.setText(response.getString("name"));
                            email.setText(response.getString("email"));
                        }
                        catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if(firebaseUser!=null){
                    if(!firebaseUser.getEmail().isEmpty())
                    {
                        email.setText(firebaseUser.getEmail());}

                }

                error.printStackTrace();

            }
        }
        );
        singletonclasshttp.getInstance(getActivity()).addtorequestque(jsonObjectRequest);

My PHP script:

?php
$username="root";
$password="";
$host = "localhost";
$dbname = "test";
$con = mysqli_connect($host,$username,$password,$dbname);
$sql = "select * from user where uid =1;";
$result = mysqli_query($con,$sql);
$data=array();

if(mysqli_num_rows($result)>0)
{

    $row = mysqli_fetch_assoc($result); 
    echo json_encode(array("name"=>$row["name"],"email"=>$row["email"],"type"=>$row["type"]));


}


?>

I need to parse the JSON and set the value for the text fields.

1
  • post your reponse class and gson response Commented Jun 13, 2019 at 18:18

2 Answers 2

1

use this site to generate a correct response class from json response

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the response. the error was due to a typos in my code.
glade to hear that. feel free to up vote and accept my answer thx.
1

You are getting JsonArray. You should use StringRequest. Then convert String to JsonArray and get JsonObject from the array.

1 Comment

Thanks for the response. the error was due to a typos in my code.

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.