2

So I used a bit of a hack to preserve the state of a WebView in a Fragment.

private enum WebViewStateHolder
{
    INSTANCE;

    private Bundle bundle;

    public void saveWebViewState(WebView webView)
    {
        bundle = new Bundle();
        webView.saveState(bundle);
    }

    public Bundle getBundle()
    {
        return bundle;
    }
}

Then

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState)
{
    View rootView = inflater.inflate(R.layout.activity_example, container, false);
    ButterKnife.inject(this, rootView);
    ...
    if(WebViewStateHolder.INSTANCE.getBundle() == null)
    {
        webView.loadUrl("file:///android_asset/index2.html");
    }
    else
    {
        webView.restoreState(WebViewStateHolder.INSTANCE.getBundle());
    }
    return rootView;
}

And

@Override
public void onPause()
{
    ...
    WebViewStateHolder.INSTANCE.saveWebViewState(webView);
    super.onPause();
}

So basically I save out the bundle on pause, then when the Fragment creates a view and this is not null, I load it back. It works perfectly okay, actually. However, if I say

getActivity().finish();

The WebView loads its data back from the bundle itself, still remembering the history of where it was.

This doesn't seem too reliable, and while this is a result of a test, I was still surprised that this happened.

When does a static object lose its data on Android? How long do these instances exist? Does Android get rid of them over time?

EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
  • possible duplicate of [Android static object lifecycle (Application act crazy)](http://stackoverflow.com/questions/1944369/android-static-object-lifecycle-application-act-crazy) –  Nov 28 '14 at 16:29
  • On a sidenote, I've just noticed the `onCreateView()`'s third parameter is the save instance state, meaning I don't even have to save it out into a static holder. Oh well. – EpicPandaForce Nov 29 '14 at 14:41

2 Answers2

1

The static variable will exist until your process is terminated.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
0

The static variable will exists until you class will be unloaded, so for example when you kill your activity or it will be killed because of memory issues

MineConsulting SRL
  • 2,340
  • 2
  • 17
  • 32