Search code examples
javaandroidandroid-asynctasktextviewandroid-runonuithread

Updating a view from RunOnUIThread works until activity is restarted


I'm updating a textView with it's setText method in a RunOnUIThread Runnable in the onPostExecute method of an AsyncTask.

The first time I run the activity, the textView updates. However when I go to another activity and return to the previous activity it no longer updates the UI.

Using the debugger I can see that the textView's mText field is being updated to the new text. However when I continue running the code the textView remains with it's default text.

Am I missing something here? I really can't see why this should be the case.

This is the onPostExecute. The method where the field is updated is checkAgainstLocations() (See below)

@Override
    protected void onPostExecute(final ArrayList<String> strings) {
        super.onPostExecute(strings);

        if (strings == null) {
            Toast.makeText(ctx, "Please check you have an internet connection", Toast.LENGTH_LONG).show();
            return;
        }

        locationsData = cleanLocations(strings);

        if (locationsData.size() < 1) {
            locationsData.add("Choose a location...");
        } else if (!locationsData.get(0).equals("Choose a location...")) {
            locationsData.add(0, "Choose a location...");
        }

        adaptor.clear();
        adaptor.addAll(locationsData);
        adaptor.notifyDataSetChanged();
        changeLocationButton.setEnabled(true);

        if (mCurrentLocation != null) {
            checkAgainstLocations();
        }
    }

This is the checkAgainstLocations() method.

private void checkAgainstLocations() {
    Geocoder gcd = new Geocoder(this, Locale.getDefault());
    List<Address> addresses = new ArrayList<>();
    if (myLocation != null) {
        try {
            addresses = gcd.getFromLocation(myLocation.getLatitude(), myLocation.getLongitude(), 1);
        } catch (IOException e) {
            Log.e("loc", "no location yet");
        }
    }

    if (addresses.size() > 0) {
        myCity = addresses.get(0).getLocality().toLowerCase();
    } else {
        myCity = "National";
    }

    new LoadPromotions().execute(myCity);

    if (locationsData.contains(myCity.toLowerCase())) {
        if (!userSelected) {
            locationsResult = myCity.toLowerCase();
            currentLocation.setText(locationsResult);
            currentLocation.postInvalidate();
        }
    }
}

Solution

  • Please make your textview static.