0

I'm developing a relatively simple Android app that has one main Activity and 7 fragments that are switched when the user switches tabs. One of the tabs is a WebView that simply loads a Twitter page within the Fragment. Because it has to load the URL, it takes about 3-4 seconds to do so and I don't want to have the user do that everytime they load this tab and switch out and come back to it, which is what is happening right now. Ideally, I'd like that after the first time the user loads the page, the page to not be reloaded everytime until necessary.

Here is the code for the webView fragment.

public class TwitterFragment extends Fragment {

    WebView webView;
    private static final String URL = "https://twitter.com/";

    public TwitterFragment() {};

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

        View rootView = inflater.inflate(R.layout.fragment_twitter, container, false);
        webView = (WebView) rootView.findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient());
        webView.loadUrl(URL);


        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
    }

According to this SO link, you can't stop onCreateView from being called everytime, which means that the URL has to be loaded everytime a fragment is resumed.

Does anyone know a way for me to circumvent this unnecessary loading of the URL everytime?

Community
  • 1
  • 1

1 Answers1

0

If you put your fragments inside ViewPager, then you have a method setOffscreenPageLimit which allow you to retain states of the offscreen fragments.

Any way you should still save your twitter data somewhere, you can write json straight to your app data file, for example store this file path in sharedmemory together with timestamp. If timestamp is too old then you would retrieve new data. You will need it when you will rotate your device screen, during config changes android will call Fragment.onSaveInstanceState. I suppose saving this file would solve all your problems.

[edit] sorry, now I see you are loading url over webview - not downloading it directly.

[edit2] this SO seem to present similar problem to yours: WebView reloading when Fragment in ViewPager is retained form BackStack, solution is to use ViewPager with setOffscreenPageLimit

Community
  • 1
  • 1
marcinj
  • 48,511
  • 9
  • 79
  • 100