Vedran Korponajić Vedran Korponajić - 9 months ago 31
Java Question

Usage of Java AsyncTask

In this course, I am creating an application "News Reader". Basicly, I need to get ID's of the news from an API(First

AsyncTask
call), then using those ID's, I get the data for of every news article(Second Async call), and in that data there is an URL that leads to that article.
When I get the URL, I store it in a DB and it is used later.
In the course, it was done with

getNews news = new getNews();
String result = news.execute("https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty").get();


, the
onPostExecute()
was not used, and I want to use it.

So, here is the class that gets the ID's of the articles(First Async Call)

public class getNews extends AsyncTask<String, Void, String>{

@Override
protected String doInBackground(String... params) {
URL url;
String result = "";
HttpURLConnection connection = null;
try {
url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
InputStream in = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while(data != -1){
char current = (char) data;
result += current;
data = reader.read();
}
}
catch (Exception e){
e.printStackTrace();
}
return result;
}

@Override
protected void onPostExecute(String s) {
try {
JSONArray jsonArray = new JSONArray(s);
//System.out.println("asasd" + jsonArray);
for(int i = 0; i< 20; i++){


}
} catch (JSONException e) {
e.printStackTrace();
}
}
}


Inside the
onPostExecute()
, when looping through the data I got, I have to make an Async call to every ID I get in that data.

So is there any way to do it without creating another class that uses
AsyncTask
?

Answer Source

Parse your data in doInBackground() instead of onPostExecute method. After you are done with parsing and extracting data from JSON response, call next API and parse its response also in same doInBackground() method.

SIDENOTE

It is always recommended to keep context separate and don't mix things. Modularity helps when extending your code with additional functionality. There is no harm in creating dedicated class which extends AsyncTask. Keeps the code clean for readibility and understanding later on.