android - WebView 在 ProgressDialog 上显示应用程序强制关闭并出现空指针异常

标签 android webview

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

我的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;

             }

            }}

编辑:

尝试访问本地托管的网站,如下所示:“http://192.168 .*.**”,其中通过添加几行代码来包含 Windows 身份验证:

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

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

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

最佳答案

现在,阻止完整 View 并不是首选方式。如果您显示进度对话框并且不允许在返回时关闭或触摸外部。用户会被黑暗大修和加载程序阻止,所以我认为你应该使用下面的方式来显示加载程序。

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

关于android - WebView 在 ProgressDialog 上显示应用程序强制关闭并出现空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35216889/

相关文章:

android - android appium 不支持滑动方法

iphone - 导出 @2x 图像以进行视网膜显示的简单方法?

objective-c - 在 cocoa 的 web View 中右键单击时重命名默认上下文菜单标题 [ Objective-C ]

java - Android - 获取从文件资源管理器中选择的.txt文件的真实路径

Android:WebView - 没有为 session 启用摄像头和麦克风

javascript - UIWebView scrollTo 应该表现流畅

webview - 如何在屏幕更改时处理 Flutter WebviewScaffold?

java - 使用应用程序类来存储数据

android - 在 android 16+ API 上保存密码

android - 如何查找设备类型和其他有关设备的信息