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

时间:2016-02-05 05:28:05

标签: android webview

尝试打开具有Windows身份验证的本地托管网站时,在进度对话框的show()函数中获取空指针异常。在" EDIT"中给出的详细信息部分:

我的webView类如下:

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;

             }

            }}

编辑:

试图访问本地托管的网站,如:&#34; http://192.168。*。**&#34;其中包括添加几行代码的Windows身份验证:

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

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

关于如何解决这个问题的任何线索.. ?? 谢谢大家。

2 个答案:

答案 0 :(得分:2)

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

<?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(new 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);

答案 1 :(得分:1)

您的progress view是全球性的,initialize只有一次,而不只是showdismiss

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

您现在正在做的是show()方法也处于if状态,这就是它仅在开始时显示的原因。