Search code examples
javaandroidandroid-fragmentswebviewactionbarsherlock

Null Pointer Exception while using onProgressChanged inside Fragment


I am using Sherlock side navigation fragments in my android application. However, i am using 6 fragments all containing a webviews with progress bar.

Here's one of the fragments:

@SuppressLint("SetJavaScriptEnabled")
public class Fragment1 extends SherlockFragment {
    private WebView mWebview;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        setHasOptionsMenu(true);

        View rootView = inflater.inflate(R.layout.fragment1, container, false);
        mWebview = (WebView) rootView.findViewById(R.id.webView1);

        mWebview.setInitialScale(1);
        mWebview.getSettings().setJavaScriptEnabled(true);



        mWebview.setWebChromeClient(new WebChromeClient() {
             public void onProgressChanged(WebView view, int progress)   
             {
                   //Make the bar disappear after URL is loaded, and changes string to Loading...
                   getActivity().setTitle("Loading...");
                   getActivity().setProgress(progress * 100); //Make the bar disappear after URL is loaded

                   // Return the app name after finish loading
                   if(progress == 100)
                   getActivity().setTitle(R.string.Fragment1);
                 }

             });


        mWebview.setWebViewClient(new WebViewClient() {
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                //Toast.makeText(activity, description, Toast.LENGTH_SHORT).show();
            }
        });

        mWebview.loadUrl("http://www.LINK");
        WebSettings zoomenable = mWebview.getSettings();
        zoomenable.setBuiltInZoomControls(true);
        WebSettings wideviewenable  = mWebview.getSettings();
        wideviewenable.setUseWideViewPort(true);

        mWebview.setDownloadListener(new DownloadListener() {
            public void onDownloadStart(String url, String userAgent,
                    String contentDisposition, String mimetype,
                    long contentLength) {
              Intent i = new Intent(Intent.ACTION_VIEW);
              i.setData(Uri.parse(url));
              startActivity(i);
            }
        });

        mWebview.setOnKeyListener(new OnKeyListener()
        {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event)
            {
             if(mWebview.canGoBack())
             {
             mWebview.goBack();
             return true;
             }

             return false;
            }
        });


        return rootView;
    }

    public class HelloWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.main_activity_actions, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle presses on the action bar items
        switch (item.getItemId()) {
            case R.id.action_search:
                mWebview.reload();
                return true;
            default:return super.onOptionsItemSelected(item);
        }
    }


}

The problem i am facing that when selecting one of the links located in the side navigation and the progress bar is not yet finished, it gives me null pointer exception in onProgressChanged method.

in the main activity i used these two line of codes to enable progress bar:

this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
this.getWindow().setFeatureInt( Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);

Here's the log cat error:

05-23 18:54:20.687: E/AndroidRuntime(20112): FATAL EXCEPTION: main
05-23 18:54:20.687: E/AndroidRuntime(20112): java.lang.NullPointerException
05-23 18:54:20.687: E/AndroidRuntime(20112):    at petra.app.Fragment1$1.onProgressChanged(Fragment1.java:45)
05-23 18:54:20.687: E/AndroidRuntime(20112):    at android.webkit.CallbackProxy.handleMessage(CallbackProxy.java:533)
05-23 18:54:20.687: E/AndroidRuntime(20112):    at android.os.Handler.dispatchMessage(Handler.java:99)
05-23 18:54:20.687: E/AndroidRuntime(20112):    at android.os.Looper.loop(Looper.java:137)
05-23 18:54:20.687: E/AndroidRuntime(20112):    at android.app.ActivityThread.main(ActivityThread.java:5297)
05-23 18:54:20.687: E/AndroidRuntime(20112):    at java.lang.reflect.Method.invokeNative(Native Method)
05-23 18:54:20.687: E/AndroidRuntime(20112):    at java.lang.reflect.Method.invoke(Method.java:511)
05-23 18:54:20.687: E/AndroidRuntime(20112):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
05-23 18:54:20.687: E/AndroidRuntime(20112):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
05-23 18:54:20.687: E/AndroidRuntime(20112):    at dalvik.system.NativeStart.main(Native Method)

Thanks in advance.


Solution

  • You can try the following code:

        mWebview.setWebChromeClient(new WebChromeClient() {
             public void onProgressChanged(WebView view, int progress)   
             {
                   //Make the bar disappear after URL is loaded, and changes string to Loading...
                   Activity activity = getActivity();
                   if (activity != null) {
                      activity.setTitle("Loading...");
                      activity.setProgress(progress * 100); //Make the bar disappear after URL is loaded
                      // Return the app name after finish loading
                      if(progress == 100)
                      activity.setTitle(R.string.Fragment1);
                    }
                 }
             });