2013-07-25 5 views
3

입력하는 동안 자동으로 검색되는 검색 막대를 구현하려고합니다.AsyncTask를 두 번 호출하는 행위

제 아이디어는 서버에서 검색 데이터를 가져 오는 AsyncTask을 사용하는 것이지만 정확히 어떻게 AsyncTask이 내 용도와 함께 작동하는지 알 수 없습니다.

내가 SearchAsyncTask이라고 가정 해 봅시다.

텍스트 필드가 나는 그래서 여기 내 질문이 있어요

new SearchAsyncTask().execute(params); 

를 호출 편집 할 때마다이의 행동이 무엇을 할 것인가? 내가 돌아와서 onPostExecute()라고 부를 많은 다른 스레드를 시작할 것인가? 아니면 다른 인스턴스가 여전히 작동하는 동안 호출되면 첫 번째 작업은 중간 작업으로 중단됩니까? 아니면 완전히 다른 무엇입니까?

이렇게하면 어떻게 될까요? 두 번째 질문에 대해서는

SearchAsyncTask a = new SearchAsyncTask().execute(params); 
... 
a.execute(params2); 
a.execute(params3); 
... 

답변

5

동일한 방법으로 내 앱의 검색 기능을 구현했습니다. 나는 TextWatcher을 사용하여 사용자가 입력 할 때 검색 결과를 작성합니다. 이를 달성하기 위해 내 AsyncTask 참조를 유지합니다. 내 AsyncTask를 선언 :

// s.toString() is the user input 
if (s != null && !s.toString().equals("")) { 

    // User has input some characters 

    // check if the AsyncTask has not been initialised yet 
    if (mySearchTask == null) { 

     mySearchTask = new SearchTask(s.toString()); 

    } else { 

     // AsyncTask is either running or has already finished, try cancel in any case 
     mySearchTask.cancel(true); 

     // prepare a new AsyncTask with the updated input    
     mySearchTask = new SearchTask(s.toString()); 

    } 

    // execute the AsyncTask     
    mySearchTask.execute(); 

} else { 

    // User has deleted the search string // Search box has the empty string "" now 

    if (mySearchTask != null) { 

     // cancel AsyncTask 
     mySearchTask.cancel(true); 

    } 

    // Clean up   

    // Clear the results list 
    sResultsList.clear(); 

    // update the UI   
    sResultAdapter.notifyDataSetChanged(); 

} 
0

, 나는 당신이이 사이트, 예를 들어 here에 대한 답을 찾을 수 있었다 생각합니다. 기본적으로 한 번만 AsyncTask 인스턴스를 실행할 수 있습니다. 동일한 인스턴스를 두 번 실행하려고하면 오류가 발생합니다.

편집 : 각 시간을 new SearchAsyncTask()으로 선언하면 수많은 응답을 받고 onPostExecute()으로 전화를 걸지만 반드시 올바른 순서는 아닙니다. 가장 좋은 방법은 변수에 AsyncTask을 저장하고 새 값을 시작하기 전에 .cancel() 메서드를 사용하는 것입니다.

+0

이 정말 질문에 대답하지 않습니다

SearchTask mySearchTask = null; // declared at the base level of my activity 

다음, TextWatcher에서, 각 문자 입력에, 나는 다음을 수행합니다. 질문의 첫 번째 부분에서는 동일한 인스턴스를 실행하지 않습니다. 하지만 그것은 두 번째 질문에 대답을합니다 – codeMagic

+0

사실, 조금 편집 해 보죠. – Nerkatel

관련 문제