Rohan
Rohan

Reputation: 1190

Saving state in Android not working

I have an activity that contains a fragment in it. The fragment has a progress bar and a text view, along with some other stuff. The progress bar and the text view both are visible sometimes, invisible at other times depending on some application logic.

What I'm trying to do is save the current state of both these views when the screen is rotated. Here is the relevant code in my fragment -

@Override
public void onSaveInstanceState(Bundle outState) {

    // pbTranscribe is my progress bar

    if (pbTranscribe != null) {
        Log.d(TAG, "saving pb visibility");
        boolean visibility = (pbTranscribe.getVisibility() == ProgressBar.VISIBLE);
        outState.putBoolean("pbVisible", visibility);
    }
}

@Override
public void onViewStateRestored(Bundle savedInstanceState) {
    super.onViewStateRestored(savedInstanceState);

    if (savedInstanceState != null) {
        Log.d(TAG, "bundle available !!");

        boolean pbVisible = savedInstanceState.getBoolean("pbVisible", false);
        Log.d(TAG, "is visible? " + pbVisible);
        if (pbVisible) {
            pbTranscribe.setVisibility(ProgressBar.VISIBLE);
        }
    }
}

The above code doesn't seem to be working for some reason. If I rotate my screen when the progress bar is visible, logcat prints all the above messages ("saving pb visibility", "bundle available !!", "is visible? true"). I know for a fact that my application logic doesn't set the visibility to invisible during this time.

Even though the value obtained from the bundle is true, the progress bar doesnt become visible, i.e. pbTranscribe.setVisibility(ProgressBar.VISIBLE); is apparently not doing its job.

Where am I going wrong ? How do I successfully maintain the progress bar state ?

I have also tried to restore the state in onCreateView() and onActivityCreated(), same results. Also, I have tried saving the text view state in a similar fashion, but that also gives the same results. Saving the text view state with android:freezesText="true" also did not do the trick.

EDIT: This is how I add the fragment to the activity, in the activity's onCreate() method -

@Override
protected void onCreate(Bundle savedInstanceState) {
    ...
    getSupportFragmentManager().beginTransaction()
            .replace(R.id.fragments_frame, new WatsonFragment())
            .commit();
    ...
}

Upvotes: 1

Views: 175

Answers (1)

Jiang Qi
Jiang Qi

Reputation: 4448

When screen rotated, Activity will call onCreate and create another WatsonFragment, modify you code to this

if(savedInstanceState==null){
getSupportFragmentManager().beginTransaction()
        .replace(R.id.fragments_frame, new WatsonFragment())
        .commit();
}

Upvotes: 2

Related Questions