Android: Can’t create handler inside thread that has not called Looper.prepare() [Solved]

Error reason:

You can't refresh the UI thread in a subthread in Android

resolvent:

//Refresh the UI using the runOnUiThread method
runOnUiThread(new Runnable() {
    @Override
    public void run() {
        //refresh UI
    }
});

common problem:

When calling locationmanager to get the current location information and upload it in real time, the reason for this error is that locationmanager needs to be used in the main thread. The following methods are recommended:

@Override
protected void onCreate(Bundle savedInstanceState) {    
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //upload location messages
    Button btnUploadGPS = (Button)findViewById(R.id.btn_upload_gps);
    if (btnUploadGPS != null){
        btnUploadGPS .setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                uploadGPS();
            }
        });
    }
}

private void uploadGPS(){    
    final LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    locationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER,
            2000,
            (float) 0.01,
            new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    asyncUploadGPS(location);
                }

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

                }

                @Override
                public void onProviderEnabled(String provider) {
                    asyncUploadGPS(locationManager.getLastKnownLocation(provider));
                }

                @Override
                public void onProviderDisabled(String provider) {
                    asyncUploadGPS(null);
                }
            }
    );
}

private void asyncUploadGPS(final Location currentLocation) {
    new Thread(new Runnable() {
        @Override
        public void run() {
            //upload loacation messages
        }
    }).start();
}

Read More: