Guillermo Herrera Guillermo Herrera - 5 months ago 22
Android Question

Run Two ASyncTasks Android Studio

Can anyone help me in fixing my code?

Apparently the problem is that I can't run more than one ASyncTask on my main thread. Can anyone give me some advise as to how I can fix my code?
Thank you!

I apologize for not commenting my code. I can explain if you guys get confused while reading it.

public class MainActivity extends AppCompatActivity {

ListView listView;
private SQLiteDatabase myDatabase;
private Cursor cursor;
boolean finished = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

listView = (ListView) findViewById(R.id.listView);
myDatabase = this.openOrCreateDatabase("HackerNews", MODE_PRIVATE, null);

Cursor cursor = myDatabase.rawQuery("SELECT * FROM ids", null);
int index = cursor.getColumnIndex("urlID");
cursor.moveToFirst();

DownloadContent content = new DownloadContent();

while(cursor != null){
String newUrl = "https://hacker-news.firebaseio.com/v0/item/" + cursor.getString(index) + ".json?print=pretty";
content.execute(newUrl);
cursor.moveToNext();
}
}

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

@Override
protected String doInBackground(String... params) {

String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int data = reader.read();

while (data >= 0) {
char current = (char) data;
result += current;
data = reader.read();
}

return result;

} catch (Exception e) {
e.printStackTrace();
return "Fail";
}
}

@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);

myDatabase.execSQL("CREATE TABLE IF NOT EXISTS ids (id INTEGER PRIMARY KEY, urlID VARCHAR)");
cursor = myDatabase.rawQuery("SELECT COUNT(*) FROM ids", null);
cursor.moveToFirst();
int count = cursor.getInt(0);

if (!(count > 0)) {

try {
JSONArray ids = new JSONArray(s);
for (int i = 0; i < ids.length(); i++) {
myDatabase.execSQL("INSERT INTO ids (urlID) VALUES ('" + ids.getString(i) + "')");
}

} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.i("message", "TABLE1 IS NOT EMPTY");
}
}
}

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

@Override
protected String doInBackground(String... params) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int data = reader.read();

while (data >= 0) {
char current = (char) data;
result += current;
data = reader.read();
}

return result;

} catch (Exception e) {
e.printStackTrace();
return null;
}
}

@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);

myDatabase.execSQL("CREATE TABLE IF NOT EXISTS content(id INTEGER PRIMARY KEY, title VARCHAR, url VARCHAR)");
cursor = myDatabase.rawQuery("SELECT COUNT(*) FROM content", null);
cursor.moveToFirst();
int count = cursor.getInt(0);

if (!(count > 0)) {

try {
JSONObject jsonObject = new JSONObject(s);
String title = jsonObject.getString("title");
String url = jsonObject.getString("url");

myDatabase.execSQL("INSERT INTO content (title, url) VALUES('" + title +"','" + url + "')");

} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.i("mess2", "table 2 is NOT EMPTY");
}
}
}
}

Answer

Each AsyncTask instance can only be run once. Simplest way to resolve this is to just create a new instance whenever you need to run it.

while(cursor != null) {
    String newUrl = "https://hacker-news.firebaseio.com/v0/item/" + cursor.getString(index) + ".json?print=pretty";
    new DownloadContent().execute(newUrl);
    cursor.moveToNext();
}