Petter K. Petter K. - 20 days ago 6
Java Question

Calling methods after new Class.execute() crash, android studio

Basically, i have an app that uses JSON. I get the JSON in new HentData.execute(); and pass it to a string variable. But when I try to acutally do something with it my program crashes.

HentData extends AsyncTask, I know it gives me a JSON string that works

INSIDE oncreate()

new HentData().execute();
jsonToArray();
arrayToText();


This crashes

But when I run them like this it works, do I have to close the HentData class somehow?

protected void onPostExecute(String resultat){
json_string = resultat;
jsonToArray();
arrayToText();
}


This is my doInBackground()

protected String doInBackground(Void... voids){
try {
URL url = new URL(json_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream IS = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(IS));
StringBuilder sb = new StringBuilder();
while((json_string = bufferedReader.readLine())!=null){
sb.append(json_string+"\n");
}

bufferedReader.close();
IS.close();
httpURLConnection.disconnect();
return sb.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

return null;
}

Answer

But when I run them like this it works, do I have to close the HentData class somehow?

protected void onPostExecute(String resultat){
    json_string = resultat;
    jsonToArray();
    arrayToText(); 
}

You don't have to close anything. This works because "async" in AsyncTask makes the code run in the background.

In other words,

new HentData().execute();  // Not waiting for result
jsonToArray(); // Continue on, even though there is no result yet --> error
arrayToText();

If you want a more flexible way to get results, see How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?

If you hate writing AsyncTasks (for HTTP methods), see Comparison of Android Networking Libraries: OkHTTP, Retrofit, Volley