WebView显示应用程序强制关闭ProgressDialog上的空指针异常

问题描述:

尝试打开具有Windows身份验证的本地托管网站时,在进度对话框的show()函数中获取空指针异常。在 “编辑” 部分给出详细说明:WebView显示应用程序强制关闭ProgressDialog上的空指针异常

我的web视图类如下:

Web.java

public class Web extends Activity { 
private WebView webView;  
final Activity activity = this; 
    public Uri imageUri; 
    ProgressDialog progressDialog; 
    private static final int FILECHOOSER_RESULTCODE = 2888; 
    private ValueCallback<Uri> mUploadMessage; 
    private Uri mCapturedImageURI = null; 
public static final int REQUEST_SELECT_FILE = 100; 
    public ValueCallback<Uri[]> uploadMessage; 



@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    this.requestWindowFeature(Window.FEATURE_PROGRESS); 
    setContentView(R.layout.activity_web); 

    webView = (WebView) findViewById(R.id.webView1); 
    webView.setWebViewClient(new MyWebViewClient()); 



    String url = "http://192.168.*.*"; 
    webView.getSettings().setJavaScriptEnabled(true); 
    webView.loadUrl(url); 
    webView.getSettings().setRenderPriority(RenderPriority.HIGH); 
    webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE); 
    webView.getSettings().setLoadWithOverviewMode(true); 

    //webView.getSettings().setUseWideViewPort(true); 

    //Other webview settings 
    webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY); 
    webView.setScrollbarFadingEnabled(false); 
    webView.getSettings().setBuiltInZoomControls(true); 
    webView.getSettings().setPluginState(PluginState.ON); 
    webView.getSettings().setAllowFileAccess(true); 
    webView.getSettings().setSupportZoom(true); 
    webView.setLayerType(View.LAYER_TYPE_HARDWARE, null); 
    webView.setDownloadListener(new DownloadListener() 
     { 
     public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) 
     { 
     //for downloading directly through download manager 
      final String filename= URLUtil.guessFileName(url, contentDisposition, mimetype); 
     Request request = new Request(Uri.parse(url)); 
     request.allowScanningByMediaScanner(); 
     request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); 
     request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename); 
     DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); 
     dm.enqueue(request); 
     } 
     }); 
} 


private class MyWebViewClient extends WebViewClient { 

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

     return false; 

    } 

    public void onLoadResource (WebView view, String url) { 

     // if url contains string androidexample 
     // Then show progress Dialog 

      if(progressDialog==null) 
      { 
      // in standard case YourActivity.this 
      progressDialog = new ProgressDialog(Web.this); 
      progressDialog.setMessage("Loading..."); 
      } 
     progressDialog.show();} 




    // Called when all page resources loaded 
    public void onPageFinished(WebView view, String url) { 

     try{ 
      // Close progressDialog 
      if (progressDialog.isShowing()) { 
       progressDialog.dismiss(); 
       progressDialog = null; 
      } 
     }catch(Exception exception){ 
      exception.printStackTrace(); 
     } 
    } 
} 


public class MyWebChromeClient extends WebChromeClient { 


public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType){ 

    // Update message 
    mUploadMessage = uploadMsg; 

    try{  

     // Create AndroidExampleFolder at sdcard 

     File imageStorageDir = new File(
           Environment.getExternalStoragePublicDirectory(
           Environment.DIRECTORY_PICTURES) 
           , "r2Reviews"); 

     if (!imageStorageDir.exists()) { 
      // Create AndroidExampleFolder at sdcard 
      imageStorageDir.mkdirs(); 
     } 

     // Create camera captured image file path and name 
     File file = new File(
         imageStorageDir + File.separator + "IMG_" 
         + String.valueOf(System.currentTimeMillis()) 
         + ".jpg"); 

     mCapturedImageURI = Uri.fromFile(file); 

     // Camera capture image intent 
     final Intent captureIntent = new Intent(
             android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 

     captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI); 

     Intent i = new Intent(Intent.ACTION_GET_CONTENT); 
     i.addCategory(Intent.CATEGORY_OPENABLE); 
     i.setType("image/*"); 

     // Create file chooser intent 
     Intent chooserIntent = Intent.createChooser(i, "Image Chooser"); 

     // Set camera intent to file chooser 
     chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS 
           , new Parcelable[] { captureIntent }); 

     // On select image call onActivityResult method of activity 
     startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE); 

     } 
    catch(Exception e){ 
     Toast.makeText(getBaseContext(), "Exception:"+e, 
        Toast.LENGTH_LONG).show(); 
    } 

} 

// openFileChooser for Android < 3.0 
public void openFileChooser(ValueCallback<Uri> uploadMsg){ 
    openFileChooser(uploadMsg, ""); 
} 

//openFileChooser for other Android versions 
public void openFileChooser(ValueCallback<Uri> uploadMsg, 
          String acceptType, 
          String capture) { 

    openFileChooser(uploadMsg, acceptType); 
} 



// The webPage has 2 filechoosers and will send a 
// console message informing what action to perform, 
// taking a photo or updating the file 

public boolean onConsoleMessage(ConsoleMessage cm) { 

    onConsoleMessage(cm.message(), cm.lineNumber(), cm.sourceId()); 
    return true; 
} 

public void onConsoleMessage(String message, int lineNumber, String sourceID) { 
    //Log.d("androidruntime", "Show console messages, Used for debugging: " + message); 

}} 






@Override 
    public boolean onKeyDown(int keyCode, KeyEvent event) { 
     if (event.getAction() == KeyEvent.ACTION_DOWN) { 
      switch (keyCode) { 
       case KeyEvent.KEYCODE_BACK: 
        if (webView.canGoBack()) { 
         webView.goBack(); 
        } else { 
         Intent i = new Intent(this, MainActivity.class); 
         startActivity(i); 
         finish(); 
        } 
        return true; 
      } 

     } 
     return super.onKeyDown(keyCode, event); 
    } 
@SuppressLint("NewApi") 
    protected void onActivityResult(int requestCode, int resultCode, Intent data){ 

      if(requestCode==FILECHOOSER_RESULTCODE) 
      { 

        if (null == this.mUploadMessage) { 
         return; 

        } 

        Uri result=null; 

        try{ 
         if (resultCode != RESULT_OK) { 

          result = null; 

         } else { 

          // retrieve from the private variable if the intent is null 
          result = data == null ? mCapturedImageURI : data.getData(); 
         } 
        } 
        catch(Exception e) 
        { 
         Toast.makeText(getApplicationContext(), "activity :"+e, 
         Toast.LENGTH_LONG).show(); 
        } 

        mUploadMessage.onReceiveValue(result); 
        mUploadMessage = null; 

      } 

      }} 

编辑:

试图访问本地托管的网站是这样的:“http://192.168。*。**”其中包括Windows身份验证通过添加几行c颂:

public void onReceivedHttpAuthRequest(WebView view, 
     HttpAuthHandler handler, String host, String realm) { 
    handler.proceed("DOMAIN\\username", "password"); 
} 

但不幸的是我得到了,因为空指针异常的强制关闭错误描述为:“尝试调用上progressDialog.show()虚方法;”

任何线索,如何我可以解决这个.. ?? 谢谢大家。

progress view是全球如此initialize一次,并且不仅仅是show,或dismiss它:

if(progressDialog == null){ 
progressDialog = new ProgressDialog(Web.this); 
progressDialog.setMessage("Loading..."); 
} 

什么你现在正在做的是你的show()方法也是if条件,这就是为什么它显示仅在开始时间。

+0

我只是不停的show()方法之外,如果状态,和它的工作,感谢.. –

+0

@ YogeshPatel欢迎您 – KDeogharkar

+0

一个更多的疑问,我可以从webview访问一个像http://192.168.*.*的IP地址...我试图访问本地托管的网站,所以我问.. –

现在阻挡全景并不是现在的首选方式。如果显示进度对话框并且不允许关闭,请按下或在外面触摸。用户将被黑暗的大修和装载机堵塞,所以我认为你应该使用下面的方式来显示装载机。

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical"> 

    <WebView 
     android:id="@+id/webView" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:visibility="gone" /> 

    <RelativeLayout 
     android:id="@+id/layout_loader" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:visibility="gone" 
     tools:visibility="visible" 
     android:gravity="center_horizontal"> 

     <android.support.v4.widget.ContentLoadingProgressBar 
      android:id="@+id/address_looking_up" 
      style="?android:attr/progressBarStyleLarge" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_centerInParent="true" 
      android:visibility="visible"/> 

    </RelativeLayout> 

</LinearLayout> 

而Java文件

wvLoad.setWebViewClient(新WebViewClient(){

 //If you will not use this method url links are open in new browser not in webview 
     public boolean shouldOverrideUrlLoading(WebView view, String url) { 
      view.loadUrl(url); 
      return true; 
     } 

     //Show loader on url load 
     public void onLoadResource (WebView view, String url) { 

     } 
     public void onPageFinished(WebView view, String url) { 
      try{ 
       loader_layout.setVisibility(View.GONE); 
       wvLoad.setVisibility(View.VISIBLE); 
      }catch(Exception exception){ 
       exception.printStackTrace(); 
      } 
     } 

     @Override 
     public void onPageStarted(WebView view, String url, Bitmap favicon) { 
      super.onPageStarted(view, url, favicon); 

      loader_layout.setVisibility(View.VISIBLE); 
      wvLoad.setVisibility(View.GONE); 

     } 
    }); 

    // Javascript enabled on webview 
    wvLoad.getSettings().setJavaScriptEnabled(true); 

    //Load url in webview 
    wvLoad.loadUrl(url); 
+0

感谢您的回复,我会给出一个镜头到您的发布代码也让你知道它是否工作.. –

+0

@YogeshPatel好吧,如果它工作正常,请接受答案。 – androidnoobdev