Search code examples
javaandroidapiandroid-volley

Requested data cannot be store inside variable in Java


I am trying getting data from an API using volley. I am trying to store it as a global variable, but it always returns null. Why?

Here is my sample code:

JsonObjectRequest jsonRequest = new JsonObjectRequest
            (Request.Method.GET, url, null, response -> {

                try {
                    if (response.getString("action").equals("success")) {

                        checkInTime = response.getString("checkin");
                        checkOutTime = response.getString("chekout");

                        System.out.println(response);


                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }, Throwable::printStackTrace);

    Volley.newRequestQueue(MainActivity.this).add(jsonRequest);

What is the problem here?

here is my api json response

{"action":"success","checkin":"08:30:25","chekout":"blank"}

Solution

  • It does not working out of the request parenthesis because this variable is temporary and it can be null if no data found.

    So you have to write looks like

    public static String checkInTime = "";
    public static String checkOutTime = "";
    

    After declaring global variable of String you can store data and can access from anywhere

    checkInTime = response.getString("checkin");
    checkOutTime = response.getString("chekout");
    

    Its actually working for me