android缺少权限为什么报NullPointerException 博客分类: 问题待解 Android Http下载报错NullPointerException缺少权限
下面是我的一个通过Http下载文件的练习,问题是在没有为程序添加网络访问权限(ndroid.permission.INTERNET)的情况为什么报的是NullPointerException,而不是指定缺少某个权限呢?
public class FileDownload extends Activity { public URL url; TextView tView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LinearLayout linearLayout = new LinearLayout(this); tView = new TextView(this); tView.setText("将要显示下载的网络数据"); Button download = new Button(this); linearLayout.addView(download); linearLayout.addView(tView); setContentView(linearLayout); download.setText("开始下载文本文件"); download.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { HttpDownloader hd = new HttpDownloader(); //注意下面的192.168.1.106是我电脑此时的ip地址,如果使用的是动态ip,请在运行时确认修改,/myapp是我的web应用,WebData.txt是web应用根目录下的一个文本文件 String webData = hd.download("http://192.168.1.106:8080/myapp/WebData.txt"); //此处报错,空指针异常 tView.setText(webData); } }); } class HttpDownloader { public String download(String urlStr){ StringBuffer sb = new StringBuffer(); String line = null; BufferedReader buffer = null; try { url = new URL(urlStr); HttpURLConnection urlConn = (HttpURLConnection)url.openConnection(); buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); while((line = buffer.readLine()) != null) { sb.append(line); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { buffer.close(); //此处报错,空指针异常 } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } } }
报错:
03-27 07:58:43.210: E/AndroidRuntime(1303): Uncaught handler: thread main exiting due to uncaught exception
03-27 07:58:43.220: E/AndroidRuntime(1303): java.lang.NullPointerException
03-27 07:58:43.220: E/AndroidRuntime(1303): at com.wly.summary.mechanism.FileDownload$HttpDownloader.download(FileDownload.java:64)
03-27 07:58:43.220: E/AndroidRuntime(1303): at com.wly.summary.mechanism.FileDownload$1.onClick(FileDownload.java:39)
03-27 07:58:43.220: E/AndroidRuntime(1303): at android.view.View.performClick(View.java:2364)
03-27 07:58:43.220: E/AndroidRuntime(1303): at android.view.View.onTouchEvent(View.java:4179)
03-27 07:58:43.220: E/AndroidRuntime(1303): at android.widget.TextView.onTouchEvent(TextView.java:6541)
03-27 07:58:43.220: E/AndroidRuntime(1303): at android.view.View.dispatchTouchEvent(View.java:3709)
03-27 07:58:43.220: E/AndroidRuntime(1303): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
03-27 07:58:43.220: E/AndroidRuntime(1303): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
03-27 07:58:43.220: E/AndroidRuntime(1303): at android.view.ViewGroup.dispatchTouch.......
由错误信息可以报的是空指针异常,为什么不是缺少权限异常的描述呢?