Alvin John Babu
Alvin John Babu

Reputation: 2070

How to fix 'Value name of type java.lang.String cannot be converted to JSONObject'

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.

Upvotes: 1

Views: 70

Answers (2)

Beyazid
Beyazid

Reputation: 1835

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

Upvotes: 1

Mohammad Sommakia
Mohammad Sommakia

Reputation: 1833

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

Upvotes: 1

Related Questions