I am trying to read an html file from a url source, but I get a nullpointerexception.
Here is my code:
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);
}
}
I tried running this program in regular Java – hardcoding the URL, and it runs fine.
However, when I run it on the android I get the “Null” messsage in my TextView.
LogCat say the NullPointerException is from sb.append(htmlLine);.
You haven’t initialized your StringBuffer Object:
You can also try this code to read content from url: