3
votes

I have a fragment which displays a WebView, in order to retain the website that is being shown I save the state like this:

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    /*Saves the currently displayed webpage and the browser history*/
    webView.saveState(outState);        
}

Then I restore it like this:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    rootView = inflater.inflate(R.layout.fragment_page_detail,
            container, false);
    webView = (WebView) rootView.findViewById(R.id.page_detail_webview);

    progressBar = (ProgressBar) rootView.findViewById(R.id.op_progress);

    webView.setWebChromeClient(new WebChromeClient() {
        public void onProgressChanged(WebView view, int progress) {

            progressBar.setVisibility(View.VISIBLE);
            progressBar.setProgress(progress);
            if (progress == 100) {

                progressBar.setVisibility(View.GONE);
            }
        }
    });
    webView.setWebViewClient(new StockStreamWebViewClient());
    webView.getSettings().setBuiltInZoomControls(true);
    /*Restores the saved browser history if there is any*/
    if (savedInstanceState != null) {
        webView.restoreState(savedInstanceState);

    } else if (mItem != null) {
        webView.loadUrl(mItem.content);

    }
    return rootView;
}

To allow the user to go back in the WebView I have this code in my Activity:

@Override
public void onBackPressed() {

    if (!clientFragment.onBackPressed()) {
        super.onBackPressed();
    }
  }
}

And this code in my Fragment:

public boolean onBackPressed() {
    if (webView != null && webView.canGoBack()) {
        webView.goBack();
        return true;
    } else {
        return false;
    }
}

When I rotate my device the screen draws correctly and the WebView restores it's previous page, but when I press back the WebView is null.

Why is this happening?

Thanks, ANkh

1

1 Answers

1
votes

SimonVT in the #android-dev correctly suggested that I might be making calls to a null or new Fragment from my Activity.

So I added this code to my Activity to save the ID of the Fragment:

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    if (clientFragment != null) {
        outState.putInt(CLIENT_FRAGMENT_ID, clientFragment.getId());
    }
}

And this code to restore the reference to the correct Fragment:

if (savedInstanceState != null
            && savedInstanceState.containsKey(CLIENT_FRAGMENT_ID)) {
        clientFragment = (PageDetailFragment) getSupportFragmentManager()
                .findFragmentById(savedInstanceState.getInt(CLIENT_FRAGMENT_ID));
    }

PageDetailFragment is my extended Fragment.

Thanks, ANkh