1

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");
            }
        }
    }
}
  • Note that all AsyncTasks share the same background thread, so the second network request will be blocked until the first competes. – Alex Cohn Jun 13 '16 at 02:58
  • Async Tasks use serial executor by default, pls refer to this [Running multiple AsyncTasks at the same time — not possible?](http://stackoverflow.com/questions/4068984/running-multiple-asynctasks-at-the-same-time-not-possible/13800208#13800208) – Protect Life Save Forests Jun 13 '16 at 06:36

1 Answers1

0

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();
}
tachyonflux
  • 20,103
  • 7
  • 48
  • 67