I want to download XML file from some URL and use it like input for my XMLPullParser.
So I wrote AsyncTask for downloading XML and call it in my code, but I have got NullPointerException:
java.lang.RuntimeException: Unable to start activity java.lang.NullPointerException: Attempt to invoke interface method 'void org.xmlpull.v1.XmlPullParser.setInput(java.io.InputStream, java.lang.String)' on a null object reference
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'void org.xmlpull.v1.XmlPullParser.setInput(java.io.InputStream, java.lang.String)' on a null object reference
Here starts my Activity and AsynTask:
public class Parsing extends AppCompatActivity {
private final static String url = "http://validURL";
InputStream parserInput;
XmlPullParser parser;
protected void onCreate(Bundle savedInstanceState) {
...
try {
parserInput = new GetXML(this).execute(url).get();
parser.setInput(parserInput,null);
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
...
}
class GetXML extends AsyncTask<String, Void, InputStream> {
private Parsing activity;
private String url;
private ProgressDialog pDialog;
public GetXML(Parsing activity/*, String url*/) {
this.activity = activity;
// this.url = url;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(activity);
pDialog.setTitle("Getting XML");
pDialog.setMessage("Loading...");
pDialog.show();
}
@Override
protected InputStream doInBackground(String... params) {
try {
URL url = new URL(this.url);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(10000 /* milliseconds */);
connection.setConnectTimeout(15000 /* milliseconds */);
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.connect();
InputStream stream = connection.getInputStream();
stream.close();
return stream;
} catch (Exception e) {
e.printStackTrace();
Log.e("AsyncTask", "exception");
return null;
}
}
@Override
protected void onPostExecute(InputStream result) {
pDialog.dismiss();
}
}
}
What is wrong in my code?
Why I am getting NullPointer exception instead of loading xml and setting it like input data for XMLPullParser?
UPD:
XML is big - about 6-8Mb.
So according to: What is a NullPointerException, and how do I fix it?
I should use ... = null;
where I have not initialize object? Or I shouldn't use it?
UPD 2:
after initializing InputStream parserInput = null;
I am getting the same error.