finki
finki

Reputation: 2123

onRestoreInstanceState - Android View Lifecycle

I have a custom View(Group)-class called RouteAutofillControlwhich basically is an EditText which gets filled with the Address resolved from my current positoin. The AsyncTask gets started in the view constructor and once it's finished I remember in a member variable that the task was finished.

I also implemented state saving on configuration changes and it works.

My problem is that at the point the view constructor is called the taskCompleted member variable hasn't been retained yet so the AsyncTask starts again.

So I am looking for a method in the View lifecycle which gets called AFTER onRestoreInstanceState.

Here are the important Parts from the View:

public class RouteAutofillControl extends LinearLayout {
    private boolean taskCompleted;

    public RouteAutofillControl(Context context, AttributeSet attrs, int defStyle) {
        if(!taskCompleted) {
            new FillRouteTask(location).execute();
        }
    }   

    @Override
    public Parcelable onSaveInstanceState() {
        final Parcelable superState = super.onSaveInstanceState();
        SavedState savedState = new SavedState(superState);
        savedState.taskCompleted = taskCompleted;
        savedState.resolvedAddress = resolvedAddress;
        return savedState;
    }

    @Override
    public void onRestoreInstanceState(Parcelable state) {
        Log.d(TAG, "onRestoreInstanceState");
        SavedState savedState = (SavedState) state;
        super.onRestoreInstanceState(savedState.getSuperState());
        taskCompleted = savedState.taskCompleted;
        resolvedAddress = savedState.resolvedAddress;
    } 
}

I did not find any information about view lifecycle methods and I am thankful for any help or advice to make it better, cheers :)

Upvotes: 1

Views: 780

Answers (1)

malrok44
malrok44

Reputation: 602

That is not quite recent, but I think that is mostly still true.

What is to retain here is that onAttachedToWindow gets called after the parent's addView process, which will call the restoreState methods on its children.

So in your case I would move my task to this callback:

@Override
public void onAttachedToWindow() {
    if(!taskCompleted) {
       new FillRouteTask(location).execute();
    }
}

Upvotes: 1

Related Questions