2016-06-13 1 views
1

누구든지 내 코드를 수정하는 데 도움을 줄 수 있습니까?두 개의 ASyncTasks 실행 Android Studio

명백하게 문제는 내 메인 스레드에서 둘 이상의 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"); 
      } 
     } 
    } 
} 
+0

모든 AsyncTasks는 동일한 백그라운드 스레드를 공유하므로 두 번째 네트워크 요청은 첫 번째 경쟁이 완료 될 때까지 차단됩니다. –

+0

비동기 작업은 기본적으로 직렬 실행 프로그램을 사용합니다. pls는이 [동시에 여러 개의 AsyncTasks 실행 - 불가능합니까?] (http://stackoverflow.com/questions/4068984/running-multiple-asynctasks-at-the-same)을 참조하십시오. 시간 초과 불가/13800208 # 13800208) –

답변

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(); 
} 
+0

감사! 그것은 그것을 고쳤다. 나는 당신의 대답을 받아들이려고했지만 웹 사이트는 나를 허락하지 않을 것입니다. –

관련 문제