Sign in
Log inSign up

Runnable won't wait for function to finish

Itay Meir's photo
Itay Meir
·Apr 3, 2017

I'm trying to run every minute a refresh for the UI. I wrote this code where I have an handler and a runnable with postdelay. Inside my runnable I have a call for a function that is returning a Map object. But every time, my runnable continues to the next lines of code before getting back the Map object from the function.

Does anyone know how to fix that? Itay.

My Code:

    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {

            Map<String, String> varList = refreshVars(firstname, lastname, id);

            String newlastdate = varList.get("newlastdate");
            String newcurrentdate = varList.get("newcurrentdate");

            /*UI changes related to "newlastdate" and "newcurrentdate"*/

            }
            handler.postDelayed(this, 60000);
        }
    };
    handler.postDelayed(runnable, 60000);

The Function:

public Map<String, String> refreshExitVars(final String FN, final String LN, final String IDN){
    final Map<String, String> list = new HashMap<>();
    Response.Listener<String> responseListener = new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {

            try {
                JSONObject jsonResponse = new JSONObject(response);
                boolean success = jsonResponse.getBoolean("success");
                if (success) {
                    String nlastdate = jsonResponse.getString("date");
                    String ncurrentdate = jsonResponse.getString("currentdate");

                    list.put("newlastdate", nlastdate);
                    list.put("newcurrentdate", ncurrentdate);

                } else {
                    int ErrorCode = jsonResponse.getInt("errorcode");
                    AlertDialog.Builder builder;
                    builder = new AlertDialog.Builder(Exit.this);
                                builder.setMessage("" + ErrorCode)
                                        .setNegativeButton("Close", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                this.finish();
                                            }
                                        })
                                        .create()
                                        .show();
                }

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

            }
        };

        RequestUIChanges requestUIChanges = new RequestUIChanges(FN, LN, IDN, responseListener);
        RequestQueue queue = Volley.newRequestQueue(Exit.this);
        queue.add(requestUIChanges);

    return list;
}