0

In my program, there are many fragments.

In the ActionBar, I have a SearchView, and result of the search is displayed in fragment0. When I go to fragment2 (that does not have Webview), I must go back fragment0 to show results.

However, when I go back to fragment0 and call the Webview, it is null.

What's problem and solution? Here is MainActivity (where search query is excuted):

Fragment fragment0 = new SearchScrActivity();
FragmentTransaction ft = getSupportFragmentManager()
                    .beginTransaction();
ft.replace(R.id.content_frame, fragment0);
ft.commit();
WebView _webview = (WebView) findViewById(R.id.webViewResult);

Here is SearchScrActivity.java

public class SearchScrActivity extends SherlockFragment {
    private WebView _webView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.activity_search_screen, container,
                false);
        _webView = (WebView) rootView.findViewById(R.id.webViewResult);
        _webView.setBackgroundColor(0x00000000);
        _webView.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);

        String meaning;
        meaning = "";       
        _webView.loadDataWithBaseURL(null, meaning, "text/html",
                "utf-8", null);
        return rootView;
    }

}
super-qua
  • 3,148
  • 1
  • 23
  • 30
Van Der Cong
  • 171
  • 2
  • 13
  • 1
    not clear to which fragment layout the webview belongs to – Raghunandan Mar 18 '14 at 15:54
  • which fragment layout has webview and in which framgent do you want to display the search result. – Raghunandan Mar 18 '14 at 15:56
  • R.layout.activity_search_screen. I called it in onCreateView of SearchScrActivity – Van Der Cong Mar 18 '14 at 15:58
  • so the `webview` belongs to `activity_search_screen.xml` and to the MainActivity Layout? – Raghunandan Mar 18 '14 at 15:59
  • yes :) I tried but it webview is null – Van Der Cong Mar 18 '14 at 16:05
  • So if the webview belongs to the framgent layout and you initialize it in `MainActivity` you get NPE as it does not belong to the current view hierarchy – Raghunandan Mar 18 '14 at 16:06
  • Sorry, in my MainActivity I called: `setContentView(R.layout.drawer_main);`. In this xml file I have a fragment, and webview in another xml file:`activity_search_screen.xml` – Van Der Cong Mar 18 '14 at 16:14
  • When you do a `FragmentTransaction` and switch fragments, it destroys the current fragment and removes it from memory. The WebView you created in the fragment will end up getting remade each time. See this question for a good solution http://stackoverflow.com/questions/8435632/how-do-i-restore-a-previously-displayed-fragment – anthonycr Mar 18 '14 at 22:21

0 Answers0