Question

I'm trying to get a reference to the instance of a fragment that's active but I'm not sure if the way I'm doing it is best or if it will cause a memory leak. In JavaScript, doing it like this will retain an instance of the Object and might cause problems, but I'm not sure about how Java would behave with GC.

The following works, but is there a better way?

public class WebframeFragment extends Fragment {

    ...
    String baseUrl;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {

            Fragment self = this; // will this cause trouble?

            this.baseUrl = getActivity().getIntent().getStringExtra(Extra.REQUEST_URL);

            webActivity.setWebView(webView);            
            webView.setWebChromeClient(new WebChromeClient());
            webView.setWebViewClient(new WebViewClient() {

                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    if (urlType(url) == urlType(self.baseUrl)){
                        return false;
                    }
                }
           }
    }

    ...    

}
Was it helpful?

Solution

I'm not sure whether it will cause a memory leak or not. If the WebView is part of the fragment then no - the Java GC handles cycles fine, otherwise - it will leak only if the WebView stays around for longer than the Fragment does.

Ideally you'd move the state that you need to reference from the WebViewClient and Fragment into a separate class and have the WebViewClient and the Fragment reference an instance of that class instead.

OTHER TIPS

It won't cause a memory problem, because you are only creating a pointer not creating a new object.

then do this,

if (urlType(url) == urlType(self.baseUrl)){                          

self = null;  
return false;

}

and after get the baseUrl you will dealloc you self var.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top