2
        for (int i = 0; i < userdataarray.length(); i++) {
            JSONObject jsonobject = userdataarray.getJSONObject(i);
            String lat = jsonobject.getString("lattitude");
            String lon = jsonobject.getString("longitude");
            la = Double.parseDouble(lat);
            lo = Double.parseDouble(lon);
            Log.i("LOG", "1");


            Handler handler = new Handler(Looper.getMainLooper());
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Log.i("LOG", "2");
                    mMap.addMarker(new MarkerOptions()
                            .position(new LatLng(la, lo))
                            .title(category));
                }
            });

The code snippet specified above is present in the onResponse() method of an okhttp call. Essentially, this for loop is being executed asynchronously. Now the problem I'm facing is that the mMap.addMarker method needs to be called for all the values of lat and long as the for loop progresses.

I have placed two Log.i() printers, one outside the UI updater and one inside. What I want is for the Logs to print alternatively:
1
2
1
2
1
2

but what's happening is
1
1
1
2
2
2

Is there any way to make it work the way I want to? Please forgive the noob code. Thanks in advance!

  • I have no idea why do you need that but your answer is here: http://stackoverflow.com/questions/20179193/calling-wait-after-posting-a-runnable-to-ui-thread-until-completion – fukanchik Oct 07 '16 at 18:37
  • Furthermore - it is much better for performance to accumulate all the markers into a list and then execute a single post _after_ the loop instead of multiple inside. – fukanchik Oct 07 '16 at 18:39
  • One thing you could do is to make your own logger class, that caches messages of type 1, and only prints a message of type 1 when the message of type 2 arrives. – Dawood ibn Kareem Oct 07 '16 at 18:59
  • Thanks, I used an array to store all the values, and then moved to the UI thread. I'm not sure why I tried to do it the other way. Thanks a lot @fukanchik ! – Anish Sekar Oct 08 '16 at 06:40

0 Answers0