'Value con of type java.lang.String cannot be converted to JSONObject

I just got an error at runtime. I understand the problem, but I could not fix it.

This is my first time working with Volley and a MySQL database. I want to save data to a MySQL database using Android and Java, and get data from edittext.

This is the error message:

W/System.err: org.json.JSONException: Value con of type java.lang.String cannot be converted 
to JSONObject
W/System.err:     at org.json.JSON.typeMismatch(JSON.java:112)
    at org.json.JSONObject.<init>(JSONObject.java:163)
    at org.json.JSONObject.<init>(JSONObject.java:176)
    at com.hanan.shareb.MainActivity$2.onResponse(MainActivity.java:75)
    at com.hanan.shareb.MainActivity$2.onResponse(MainActivity.java:65)
    at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:78)
    at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
    at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:106)
    at android.os.Handler.handleCallback(Handler.java:873)
W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:6986)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1445)

This is my PHP code

<?php
 if ($_SERVER['REQUEST_METHOD'] == 'POST') {

$name = $_POST['name'];
$quantity = $_POST['quantity'];
  
require_once 'connect.php';

$sql = "INSERT INTO products(name,quantity) VALUES ('{$name}','{$quantity}')";

if (mysqli_query($conn,$sql)){
    $response ["sucsess"] = "1" ;
    $response ["message"] = "sucsess";

    echo json_encode($response);
    mysqli_close($conn);
}else{
    $response ["sucsess"] = "0" ;
    $response ["message"] = "failed .. error";

    echo json_encode($response);
    mysqli_close($conn);
}} ?>

And this is my Java / Android code

public class MainActivity extends AppCompatActivity {

    private EditText product_name ,priduct_num , pruduct_qantity;
    private Button btn_send_request;
    private ProgressBar loading;
    private static String URL_REGIST = "https://hananmaiyas77909.000webhostapp.com/index.php";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        priduct_num = findViewById(R.id.pruducNum);
        product_name = findViewById(R.id.pruductName);
        pruduct_qantity = findViewById(R.id.pruducQuantity);
        btn_send_request = findViewById(R.id.sendRequest);
        loading = findViewById(R.id.loading);

        btn_send_request.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Requset();
            }
        });

    }

    private void Requset(){
        loading.setVisibility(View.VISIBLE);
        btn_send_request.setVisibility(View.GONE);

        final String name = this.product_name.getText().toString().trim();
        final String quantity = this.pruduct_qantity.getText().toString().trim();
      //  final String num = this.priduct_num.getText().toString().trim();

        StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_REGIST, new
                Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                     //       String result = EntityUtils.toString(entity);


             //               JSONObject jsonObject = new JSONObject(response);
                          //  response = getJSONUrl(url);
                      //      JSONArray array=    new JSONArray(resultdata);
                            JSONObject jsonObject = new JSONObject(response);

                         //   JSONObject jsonObject = new JSONObject("{"+response+"}");
                            String success = jsonObject.getString("success");
                            if (success.equals("1"))
                            {
                                Toast.makeText(MainActivity.this, "requested success >>> ", Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            Toast.makeText(MainActivity.this, " error >>> "+e.toString(), Toast.LENGTH_SHORT).show();
                            loading.setVisibility(View.GONE);
                            btn_send_request.setVisibility(View.VISIBLE);
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(MainActivity.this, " error >>> "+error.toString(), Toast.LENGTH_SHORT).show();
                loading.setVisibility(View.GONE);
                btn_send_request.setVisibility(View.VISIBLE);
            }
        })
        {
            @Nullable
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> params = new Hashtable<>();
                params.put("name","name");
                params.put("quantity","quantity");
                return params;
            }
        };
        RequestQueue requestQueue= Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source