0

I have problem running this method, it doesn't execute in order.

private Double balance;

public double getBalance(Address address){
    balance=0.0;
    String url = urlAPI+address.toString();

    RequestQueue reqQueue;
    reqQueue = Volley.newRequestQueue(this);

//Comment #1

    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET, url, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try {

//Comment #2

                        if (response.get("data").toString() != "null") {
                            balance = Double.parseDouble(response.get("data").toString()) / 100000000;
                        } else {
                            balance = 100.00000001;
                        }
                        ;
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                }
            }
    );
//Comment #3

    reqQueue.add(jsonObjReq);

    return balance;
}

Its execute order goes Comment #1 -> #3 -> #2. It even finishes tasks outside the method before return to finish #2. This causes incorrectly return value.

Any help would be much appreciated.

Zoe
  • 27,060
  • 21
  • 118
  • 148
TheKOM
  • 3
  • 2
  • 2
    This is asynchronous, it means that the code is not waiting for the response. When the response is received, the `onResponse` method will be called. To correct your logic, the `Response.Listener` must send the `balance` you received where it is needed. – AxelH Apr 26 '19 at 11:00
  • https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java/513839#513839 – Gyro Gearless Apr 26 '19 at 11:01
  • Thank you so much @AxelH I finally be able to sleep peacefully tonight. – TheKOM Apr 26 '19 at 13:46
  • Also thanks to @Gyro Gearless , Zoe and Thomas for collecting all the mistakes. – TheKOM Apr 26 '19 at 13:51

0 Answers0