Luke Swain
Luke Swain

Reputation: 25

Android: Async Task | Do in background freezes up UI?

I am having an issue and have looked all over the place (youtube, dev sites) for a solution and am unable to find one.

The UI in my application is hanging when the volley connection is started, I added it to an AsyncTask overriding DoInBackground method but it still hangs.

The code I have handling the connection through volley is:

public class DoInBackground extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... arg0) {
        //Adding cameras from server using volley...
        String url = "FullUrlHere";
        JSONArray jArray = new JSONArray();

        JsonArrayRequest jArrayReq = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                //Response received
                try {
                    int sizeOfArray = response.getInt(0);
                    String element = response.getString(1);

                    //Toast.makeText(getApplicationContext(), "Size: " + sizeOfArray, Toast.LENGTH_LONG).show();
                    //Now we have the size of array, now to cycle through them
                    for (int i = 1; i < sizeOfArray + 1; i++) {
                        //Cycle through
                        String nextAddress = response.getString(i);
                        //Put into our array
                        cameraAddresses.add(nextAddress);
                    }

                    for (String address : cameraAddresses) {
                        String camAddress = address;
                        //Toast.makeText(getApplicationContext(), latitudeValue, Toast.LENGTH_LONG).show();

                        //Start reverse geo coding. (Turning address into coordinates.)
                        Geocoder camLocationGeocoder = new Geocoder(getApplicationContext());
                        List<Address> addresses;
                        addresses = camLocationGeocoder.getFromLocationName(address, 1);
                        if (addresses.size() > 0) {
                            double latitude = addresses.get(0).getLatitude();
                            double longitude = addresses.get(0).getLongitude();
                            //Add markers.
                            Marker camera = mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("Possible Speed Camera.").icon(BitmapDescriptorFactory.fromResource(R.drawable.camera_placemarker)));
                            cameraList.add(camera);
                        }

                    }
                } catch (Exception e) {
                    //Error caught.
                    //Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //Error
                //Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_LONG).show();
            }
        });

        MySingleton.getInstance(getApplicationContext()).addToRequestQueue(jArrayReq);
        return null;
    }
}


private void addLocations() {
    //Below code to be performed on BG thread

    for (Marker camera : cameraList) {
        camera.remove(); //Remove camera, we will re-add them in a while.
    }
    cameraList.clear(); //Remove all cameras from arrayList

    //Execute Task
    new DoInBackground().execute();
}

Upvotes: 0

Views: 727

Answers (2)

Kevin Lopez
Kevin Lopez

Reputation: 77

Did you try to override onPostExecute or onProgressUpdate?

AsyncTask have 4 methods:

  • onPreExecute() -> runs in main thread before doInBacground() will be called
  • doInBackground(Object[] params) -> runs in background and cannot interact with UI
  • onProgressUpdate(Object[] values) -> runs in main thread while you call the method publishProgress(Object... values) in doInBackground
  • onPostExecute(Object result) -> runs in main thread when doInBackground ends the task

Im not sure if the methods that you are using to create the cameras must be executed in the main thread, but if youd didn't solve the problem yet, you can try to instance the new cameras into the onProgressUpdate and call publishProgress from doInBackground each time that you have the data to create a camera.

I hope it helps you.

Upvotes: 1

Marcin Orlowski
Marcin Orlowski

Reputation: 75629

Do in background freezes up UI?

doInBackground as name indicates is running on seapare, no UI thread. It will not block the UI thread (it may however cause i.e. heavy load that would affect the UI thread as well, but that other story).

Upvotes: 0

Related Questions