片段生命周期和IllegalStateException

时间:2015-09-21 19:34:14

标签: android android-fragments

我的应用程序有一个名为HomeActivity的活动,其中包含一个包含webview的片段。

当加载webview时,会有一个打开和关闭的progressdialog。

我的应用程序使用Parse.com接收一些推送,当收到推送时,它会打开HomeActivity。当应用程序没有打开时,一切正常,但是当应用程序已经在后台时,它会崩溃(并非总是),并出现错误:

java.lang.IllegalStateException: Fragment HomeActivityFragment{11e3f482} not attached to Activity
        at android.app.Fragment.getResources(Fragment.java:788)
        at com.myieseg.fragment.HomeActivityFragment$1.onPageStarted(HomeActivityFragment.java:64)

它在线上崩溃了:

 dialog = ProgressDialog.show(getActivity(), null,getResources().getString(R.string.plzwait));

我想,我会添加一个catch IllegalStateException,因为在这种情况下我不关心对话框,但我想了解如何正确处理这个错误。

感谢

这是片段代码:

public class HomeActivityFragment extends Fragment {

    private WebView webView = null;

    ProgressDialog dialog;

    public HomeActivityFragment() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Bundle bundle = this.getArguments();
        int url = R.string.defaulturl;
        if (bundle != null) {
            url = bundle.getInt("index", R.string.defaulturl);            
        }

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



         webView = (WebView) v.findViewById(R.id.webView);
        if(webView!=null){
            webView.getSettings().setDomStorageEnabled(true);
            webView.getSettings().setJavaScriptEnabled(true);

            webView.setWebViewClient(new WebViewClient() {

                public void onPageStarted(WebView view, String url, Bitmap favicon) {                
                    dialog = ProgressDialog.show(getActivity(), null,getResources().getString(R.string.plzwait));
                       dialog.setCancelable(true);                    
                    super.onPageStarted(view, url, favicon);
                }

                public void onPageFinished(WebView view, String url) {
                    dialog.dismiss();
                    super.onPageFinished(view, url);
                }

                public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                    dialog.dismiss();                    
                    Toast.makeText(getActivity(), getResources().getString(R.string.errorwebview), Toast.LENGTH_LONG).show();
                    super.onReceivedError(view, errorCode, description, failingUrl);
                }
            });

            webView.loadUrl(getResources().getString(url) );

        }

        return v;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if(dialog!=null){
            dialog.dismiss();
        }
    }
}

0 个答案:

没有答案