Vedran Korponajić Vedran Korponajić - 1 year ago 72
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

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("").get();

, the
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>{

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 =;
while(data != -1){
char current = (char) data;
result += current;
data =;
catch (Exception e){
return result;

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) {

Inside the
, 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

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.


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download