android – WebView reloading when Fragment in ViewPager is retained form BackStack-ThrowExceptions

Exception or error:

Here is a code for a basic Fragment which contains a WebView.
WebFragment.java

public class WebFragment extends Fragment {
String TAG = "WebFragment";
private WebView webView;
private String currentUrl = "http://www.google.com";

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    return inflater.inflate(R.layout.webview_layout, null);
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    webView = (WebView) getView().findViewById(R.id.helloWebview);
    initWebView();
    webView.loadUrl(currentUrl);
}

@SuppressLint("SetJavaScriptEnabled")
private void initWebView() {
    webView.getSettings().setJavaScriptEnabled(true);
    webView.addJavascriptInterface(new JavaScriptInterface(), "HTMLOUT");
    webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            Log.e(TAG, "Loding...");
            super.onPageStarted(view, url, favicon);
        }
    });
}

class JavaScriptInterface {
    public void showHTML(String html) {
    }
}
}

I have 2 more basic fragments also(which doesn’t have WebView). Then I put all these 3 Fragments in ViewPager(WebFragment, Fragment1 and Fragment2respectively) using FragmentAdapter. And I added android:configChanges="orientation|screenSize" in AndroidManifest.xml(So WebView will not realod on configration change).
Now my problem is, While running app I changed the 1st page (WebFragmet) of ViewPager to 2nd page(Fragment1) and again I came back to 1st page. So no problem WebFragment is as it is.

Now again I changed the ViewPager like this WebFragment–>Fragment1–>Fragment2 and came back to 1st page by reversing the direction of above action. But at that time I saw the WebView in WebFragment is reloading.

And one more problem, whenever the WebView started loading I can see 2 log entry like.

WebFragment Loading...
WebFragment Loading...

So my question is :
1) How can I prevent WebView reloading when the WebFragment is retained from BackStack?
2) Why here WebView loading twice?

Just see this question and help me(Prevent WebView reloads in FragmentPagerAdapter?).

How to solve:

In your main activity where you have defined viewpager

after the declaration of viewpager like this line :
ViewPager viewpager = (ViewPager) findViewById(R.id.pager);

add this line :

viewpager.setOffscreenPageLimit(2);

This will prevent your fragment from recreated upto swipe of two screens,so when you will return from 3rd page to 1st page in viewpager,your webview will not reload.

###

This is a classic case of falling victim to the easy patch-fix of overriding android:configChanges to solve a problem. Unfortunately there are multiple reasons why a config change will occur. So simply catching for a screen size change will miss a lot of them…as you have discovered.

First, completely remove android:configChanges. Then add the following to your WebView fragment.

protected void onSaveInstanceState(Bundle outState) {
  webView.saveState(outState);
}

Adjust your WebView fragment’s onActivityCreated method to include the following:

public void onActivityCreated(Bundle savedInstanceState) {
    webView = (WebView) getView().findViewById(R.id.helloWebview);
    initWebView();

    if (savedInstanceState != null)
        webView.restoreState(savedInstanceState);
    else
        webView.loadUrl(currentUrl);

}

That should get you going in the right direction. Note, calling a WebView‘s saveState() will not save display data. Eg, input tags will not perserve user input. You’ll need to parse through the webpage manually to persist that data. Depending on what you are using the WebView for, this will be a major pain.

###

Well for fragments use like this.

A extends Fragment

{

   static  WebView w;

   View v;

   private Handler handler = new Handler(){

    @Override
    public void handleMessage(Message message) {

        switch (message.what) {
            case 1:{
                webViewGoBack();
            }break;
        }
    }

    private void webViewGoBack() {
        w.goBack();

        // TODO Auto-generated method stub

    }
};

@Override

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle    savedInstanceState){

 v = inflater.inflate(R.layout.webs, container, false);

 w=(WebView)v.findViewById(R.id.webView1);

//w.loadUrl("");

}

 w.setOnKeyListener(new OnKeyListener(){

 @Override

 public boolean onKey(View v, int keyCode, KeyEvent event) {

            // TODO Auto-generated method stub
   if((keyCode==KeyEvent.KEYCODE_BACK)&& w.canGoBack())

            {

                handler.sendEmptyMessage(1);

                return true;

            }
            return false;
        }

     });

Leave a Reply

Your email address will not be published. Required fields are marked *