Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: "Calling thread must be a prepared Looper thread" error when I use AsyncTask

I've created a AsyncTask to retrieve a GPS position with a 20-meter accuracy. I would like to execute a while do cycle until accuracy is accetable.

The problem is that I got an exception when I request an update of position.

java.lang.NullPointerException: Calling thread must be a prepared Looper thread.

This is the piece of code that goes in error

@Override
protected String doInBackground(Void... params) {
if (ActivityCompat.checkSelfPermission(activity, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(activity, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return null;
            }
            mLocationRequest.setInterval(100);
            mLocationRequest.setPriority(100);
            mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
            while (mLastLocation == null || (mLastLocation.getAccuracy()>Float.parseFloat("20.0") && mLastLocation.hasAccuracy())){
                try {
                    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mLocationRequest,activity);
                    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
                } catch (SecurityException secex) {

                }
            }

            return null;
        }
like image 316
michael Avatar asked Nov 30 '25 14:11

michael


1 Answers

I had troubles with this a full work day. I have the FusedLocationApi running in background within a Service.

What I a did -I read it somewhere else- is add Looper.getMainLooper() as the last parameter of requestLocationUpdates().

So, instead of this

LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mLocationRequest,activity);

You'll have

LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this, Looper.getMainLooper());

If your read the whole FusedLocationProviderApi page, you will see that the method will do different thing depending on the parameters.

like image 85
Pedro Varela Avatar answered Dec 02 '25 02:12

Pedro Varela



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!