Search code examples
androidandroid-asynctaskandroid-locationlocationlistener

Can't create handler inside thread that has not called looper.prepare() asynctask


I am using the following async class to show dialog and to get the current location of user but getting the above error.

ProgressDialog progressDialog;

class LoadJsonTask extends AsyncTask<Void, Void, Void> {
      protected void onPreExecute() {
      progressDialog = ProgressDialog.show(NewTraveler.this, "", "Loading...");
    }

@Override
protected Void doInBackground(Void... arg0) {
try {
         // Acquire a reference to the system Location Manager
        LocationManager locationManager = (LocationManager) this
                    .getSystemService(Context.LOCATION_SERVICE);

    // Define a listener that responds to location updates
        LocationListener locationListener = new LocationListener() {
            public void onLocationChanged(Location location) {
                latitude = location.getLatitude();
                longitude = location.getLongitude();

                System.out.println("Latitude:- " + latitude);
                System.out.println("Longitude:- " + longitude);
        }

        public void onStatusChanged(String provider, int status,
                Bundle extras) {
        }

        public void onProviderEnabled(String provider) {
        }

        public void onProviderDisabled(String provider) {
        }
    };

    // Register the listener with the Location Manager to receive
    // location
    // updates
    locationManager.requestLocationUpdates(
            LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

        } catch (Exception e) {
                System.out.println("error ".getMessage());
            }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        progressDialog.dismiss();
    }
}

in my onCreate method i am calling the above class using
new LoadJsonTask().execute();

Please help me out.


Solution

  • Use this

    // Define a listener that responds to location updates
            LocationListener locationListener = new LocationListener() {
                public void onLocationChanged(Location location) {
                    latitude = location.getLatitude();
                    longitude = location.getLongitude();
    
                    System.out.println("Latitude:- " + latitude);
                    System.out.println("Longitude:- " + longitude);
            }
    
            public void onStatusChanged(String provider, int status,
                    Bundle extras) {
            }
    
            public void onProviderEnabled(String provider) {
            }
    
            public void onProviderDisabled(String provider) {
            }
        };
    

    outside the doInBackground method.