我正在尝试从 url 源读取 html 文件,但出现空指针异常。这是我的代码:
public class NetworkThread extends AsyncTask<String, Integer, String> {
URL url;
StringBuffer sb;
InputStream is;
@Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
String webUrl = etUrl.getText().toString();
try {
url = new URL(webUrl);
BufferedReader in = new BufferedReader(
new InputStreamReader(url.openStream()));
String htmlLine;
while ((htmlLine = in.readLine()) != null)
sb.append(htmlLine);
in.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "Bad URL";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "Input / Output";
} catch (NullPointerException e) {
e.printStackTrace();
return "Null";
}
return sb.toString();
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
html.setText(result);
}
}
我尝试在常规 Java 中运行这个程序——对 URL 进行硬编码,它运行良好。
但是,当我在 android 上运行它时,我在 TextView 中收到“Null”消息。
LogCat 说 NullPointerException 来自sb.append(htmlLine); .