运行两个ASyncTasks Android Studio

时间:2016-06-13 01:04:05

标签: android android-studio android-asynctask

任何人都可以帮我修复我的代码吗?

显然问题是我无法在主线程上运行多个ASyncTask。谁能给我一些关于如何修复我的代码的建议? 谢谢!

我为没有评论我的代码而道歉。如果你们在阅读时感到困惑,我可以解释一下。

 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");
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

每个AsyncTask实例只能运行一次。解决此问题的最简单方法是在需要运行时创建一个新实例。

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