这个想法是当没有可用的互联网连接时,向用户显示我的自定义对话框,表明没有连接。否则,在WebView中加载页面时,显示ProgressDialog以显示加载完成时页面正在加载和关闭。当有互联网连接这个代码有效,但如果没有,它会崩溃,我找不到错误的位置。
package com.tariknotebook;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
public class NoteBook extends Activity {
/** Called when the activity is first created. */
WebView web;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
web = (WebView) findViewById(R.id.browserMine);
web.setWebViewClient(new HelloWebViewClient());
web.getSettings().setJavaScriptEnabled(true);
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
web.loadUrl("http://m.seslisozluk.com");
}
ProgressDialog dialog;
Dialog connDialog;
@Override
protected Dialog onCreateDialog(int id) {
switch(id)
{
case 1:
dialog = ProgressDialog.show(NoteBook.this, "Loading",
"Loading.. Please wait.");
break;
case 2:
connDialog = new Dialog(getApplicationContext());
connDialog.setContentView(R.layout.connection);
connDialog.setTitle("No Internet Connection");
Button closeButton = (Button) findViewById(R.id.closeButton);
closeButton.setOnClickListener(new closeButtonOnClickListener());
connDialog.show();
break;
}
return super.onCreateDialog(id);
}
private class closeButtonOnClickListener implements OnClickListener
{
public void onClick(View v) {
connDialog.dismiss();
};
}
private class HelloWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
ConnectivityManager conStatus = (ConnectivityManager) view.getContext().getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
if(conStatus.getActiveNetworkInfo().isConnected() && conStatus.getActiveNetworkInfo() != null)
showDialog(1);
else
showDialog(2);
}
@Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
dialog.dismiss();
}
}
}
这也是错误日志:
答案 0 :(得分:2)
当您发布错误消息时,您应该告诉我们哪一行对应。
通过将代码粘贴到文本编辑器中,我相信第83行是:
if(conStatus.getActiveNetworkInfo().isConnected() && conStatus.getActiveNetworkInfo() != null)
这强烈暗示conStatus为null,并且您正在尝试调用不存在的对象的方法。
你应该先检查它是非空的。