1

I'm retrieving data from my server through JSON using Volley JSONObjectRequest to achieve this. After getting the JSON response, I want to save it into a variable and use it through out the activity. Below is my code sample:

private String description;
private int status;
private boolean validateIntegrationCode() {
    if (checkNetwork()) {
        String url = "sample url";

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    status = response.getInt("status");// ** STATUS IS 1 HERE **
                    description = response.getString("description");

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });

        mQueue.add(request);
    } else {
        // No network, check from SQLite
    }
    if (status == 1) { // ** STATUS IS 0 HERE **
        return true;
    } else {
        return false;
    }
}

When I check the status value before returning true or false, the value of status is now 0 and the description also returns null.

My JSON response:

{"status":1,"description":"Integration code is valid"}
Mike
  • 697
  • 1
  • 9
  • 21

3 Answers3

2

I have updated my answer as below,

    private int status;
    private String description;

    private void callRequest() {

        // Initialize a new RequestQueue instance
        RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);

        // Initialize a new JsonObjectRequest instance
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
                Request.Method.GET,
                "URL",
                null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            status = response.getInt("status");// ** STATUS IS 1 HERE **
                            description = response.getString("description");

                            checkStatus();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
                    }
                }
        );

        // Add JsonObjectRequest to the RequestQueue
        requestQueue.add(jsonObjectRequest);
    }

    private void checkStatus(){
        if(status == 1){
            // do what do you need to do id status == 1
        }else{
            // do what do you need to do id status == 0
        }
    }

Try this and let me know the updates Thanks!

Anupa Dayaratne
  • 358
  • 1
  • 8
  • Can't return boolean inside a `void onResponse`. – Mike Sep 26 '18 at 02:58
  • Hi I have changed my answer, Please try this. Thanks.! – Anupa Dayaratne Sep 26 '18 at 03:25
  • Just realised that the checking should be handle inside the onResponse. Your answer should works too as it is quite similar to my accepted answer. By the way, thanks so much for spending your precious time in helping me out. – Mike Sep 26 '18 at 03:47
1

You should declare status as int instead of String.

private int status=0;

You can try this way

                status = response.getInt("status");
                description = response.getString("description");
                if (status == 1) { 
                 checkingStatus(status);
                } else {
                 checkingStatus(status);
                }

Then

public void checkingStatus(int status){
        if(status == 1){
            // do your code
        }else{
            // do your code
        }
    }
IntelliJ Amiya
  • 74,896
  • 15
  • 165
  • 198
  • Ops, sorry. My code is `int`, I had wrongly typed it here just now. BTW, I had checked the output of status before compare `if (status == 1)` and the value is 0 – Mike Sep 26 '18 at 02:41
  • 1
    I change my function to void then create a `private boolean` variable but I still get `null` when displaying the `Boolean` value after calling my function. Only inside `onResponse` it is showing the correct value. – Mike Sep 26 '18 at 03:19
  • 1
    Just realised that it should be handle inside the onResponse. Your answer should works too as it quite similar to my accepted answer. By the way, thanks so much for spending your precious time in helping me out. – Mike Sep 26 '18 at 03:46
1

The volley request is an asynchronous call. It doesn't block the code till the response is received. So what is happening is your check for if(status==1) is happening before the volley response is received. Hence it is 0.

What you should do:

1) Make your function return type void.

2) In onResponse, put the code

if (status == 1) { // ** STATUS IS 0 HERE **
        statusBoolean = true;
    } else {
        statusBoolean = false;
}
nupadhyaya
  • 1,909
  • 1
  • 14
  • 14
  • Like in my answer. Remove the return type for the function. Create a variable statusBoolean and set it's value to true or false – nupadhyaya Sep 26 '18 at 02:55
  • I get `null` when displaying the statusBoolean value after calling my function. Still displaying the correct value inside `onResponse` only. – Mike Sep 26 '18 at 03:18
  • You shouldn't display it after calling the function. Anything you do after the network request must happen in the onResponse of the volley request. – nupadhyaya Sep 26 '18 at 03:20
  • Oh, so I can't put the response data into variable and use it in my `onCreate` or main class? In a case of JSON response returning details or list of products, I need to insert it into `ArrayList` and populate the listing all inside the Volley `onResponse` is it? – Mike Sep 26 '18 at 03:29
  • Add everything else inside a function and call that function from the JSON response – nupadhyaya Sep 26 '18 at 03:32
  • Noted, thank you. I've accepted your answer as you're the first one pointing it out to handle it inside the onResponse. – Mike Sep 26 '18 at 03:44