0

Trying to get a value from my PHP API, on android, using volley... my API is working fine, returning the value I want, but on my android I can seem to save the value on a variable.

this is my PHP script

<?php

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

$titu = $_POST['titulo'];
$id_use = $_POST['id_user'];
$difi = $_POST['dificuldade'];


$user = "root";
$pass = "";
$host= "localhost";
$dbname="check";

$con = mysqli_connect($host,$user,$pass,$dbname);
$sql="insert into trilhos(titulo,id_user,dificuldade) 
values('".$titu."','".$id_use."','".$difi."');";


$r = mysqli_query($con,$sql);

$id_trilho =mysqli_insert_id($con);

$result = array();
echo json_encode(array("result"=>$id_trilho));

mysqli_close($con);
}

on my android studio, I try to get the value like this, I send 3 values to insert into the database, and then I want to return the id of the row I inserted back to android. I have looked at many answers on StackOverflow but I just can't seem to understand and solve my problem.

public void insert(String titulo, String id_trilho, String dif) {
    url = "http://192.168.1.68/loginsignup/insertTrilho.php?titulo=" + titulo +"&id_user="+ id_trilho+ "&dificuldade=" + dif + "";
    Log.i("Http", "" + url);
    RequestQueue requestQueue = Volley.newRequestQueue(InserirTrilho.this);
    StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            try {
                JSONObject jsonObject = new JSONObject(response);
                JSONArray jsonArray = jsonObject.getJSONArray("result");
                JSONObject jsonObject1 = jsonArray.getJSONObject(0);
                String id = jsonObject1.getString("id_trilho");
                Toast.makeText(InserirTrilho.this, id, Toast.LENGTH_SHORT).show();


                SharedPreferences shared_id = getSharedPreferences("Mytrilho", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = shared_id.edit();
                editor.putString("id", id);


                editor.commit();
                Intent intent = new Intent(InserirTrilho.this, MapsActivity.class);
                startActivity(intent);

            } catch (JSONException e) {
                e.printStackTrace();
                Toast.makeText(InserirTrilho.this, "Dados Errados", Toast.LENGTH_SHORT).show();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.i("HttpError","erro"+error);
        }

    });
    requestQueue.add(stringRequest);
}

keep getting a thrown exception, can someone help me out, thank you in advance

Sapo121
  • 71
  • 1
  • 12
  • use this `jsonObject.getString("id_trilho");` instead of `jsonObject1.getString("id_trilho");` – Pavneet_Singh Apr 16 '18 at 14:01
  • This line of code `json_encode(array("result"=>$id_trilho));` will not give you the JSON structure you think you are trying to parse! Please update your question and provide an example of the JSON response your are getting back. I find it hard to believe that you are not getting an error. – Barns Apr 16 '18 at 14:08
  • Pavneet_Singh solved my problem, for some reason i cant edit my answer so that other people can see it correctly, but his answer solved my problem – Sapo121 Apr 16 '18 at 16:45

1 Answers1

3

The issue is, url is a type of Get request but the method is in java request is of type POST so you need to send data as part of the request using as Body so

see how to send a POST request using volley with string body?


As commented , Your response is jsonobject not array so use

JSONObject jsonObject = new JSONObject(response);
String id = jsonObject.optString("result");    

instead of

JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("result");
JSONObject jsonObject1 = jsonArray.getJSONObject(0);
String id = jsonObject1.getString("id_trilho");

or to get what you want then use

$result = array();
$result["result"]= array();
array_push($result["result"],array("id_trilho"=>$id_trilho)); // assume $id_trilho =0
echo json_encode($result);
// output {"result":[{"id_trilho":0}]}

or simply use

$id_trilho = 0;
$result = array();
array_push($result,array("id_trilho"=>$id_trilho));
echo json_encode($result);
// output [{"id_trilho":0}]
// then use JSONArray jsonArray = new JSONArray(response);
// JSONObject jsonObject1 = jsonArray.getJSONObject(0);
// String id = jsonObject1.getString("id_trilho");
Pavneet_Singh
  • 36,884
  • 5
  • 53
  • 68
  • thanks for your answer, i have tried everything you said, but i keep getting the same error org.json.JSONException: Value
    – Sapo121 Apr 16 '18 at 15:29
  • @Sapo121 there is an error in your sql query so rectify it's syntax as shown in the answer – Pavneet_Singh Apr 16 '18 at 15:36
  • everytime i test the script using postman i get a result and it inserts a new row on my DB, on my android i cant get a response – Sapo121 Apr 16 '18 at 15:41
  • @Sapo121 use this `JSONObject jsonObject = new JSONObject(response); String id = jsonObject.optString("result");` – Pavneet_Singh Apr 16 '18 at 15:45
  • {"result":[{"id_trilho":48}]} – Sapo121 Apr 16 '18 at 15:45
  • @Sapo121 try the updated code,which is at the top for parsing – Pavneet_Singh Apr 16 '18 at 15:48
  • org.json.JSONException: Value
    () { and 106 is JSONObject jsonObject = new JSONObject(response);
    – Sapo121 Apr 16 '18 at 15:59
  • @Sapo121 use log to see the value of `response` and post it here because it clearly seems like you are receiving some other value – Pavneet_Singh Apr 16 '18 at 16:02
  • response=0 , this does not make any sense... sorry for bothering you, but i have stuck with this for some time, i simply need last_inserted_id from my query and pass it to my android so i can work with it. – Sapo121 Apr 16 '18 at 16:08
  • make sure that your are hitting the right url, seems like you are using get url and using post, [How to send a POST request using volley with string body?](https://stackoverflow.com/questions/33573803/how-to-send-a-post-request-using-volley-with-string-body) – Pavneet_Singh Apr 16 '18 at 16:14
  • that could be the problem, i will try to fix it and get back to you, i used GET for some other stuff but i did not need to insert anything like now. – Sapo121 Apr 16 '18 at 16:22
  • I got it to work, just changed the way i sent my data @Override protected Map getParams() throws AuthFailureError { MapstringMap = new HashMap<>(); stringMap.put("titulo",titulo); stringMap.put("id_user",id_user); stringMap.put("dificuldade",dif); return stringMap; } }; and its working fine, thank you for your help – Sapo121 Apr 16 '18 at 16:44
  • i am glad that i could help, happy coding – Pavneet_Singh Apr 16 '18 at 16:45