2011-09-11 5 views
0

나는 사용자가 비즈니스 이름을 입력 할 수있는 EditText가 있습니다. 나는 또한 데이터베이스에서, 그들은 입력 한 키워드를 확인하고 무엇을 검색하는 이미 데이터베이스에 추가 된 사항에 대한 사용자의 제안이 글고 아래의 ListView ...에서 사용자 유형으로 지금Android 효율적인 AsyncTask

<EditText android:id="@+id/txtBusinessName" android:hint="Name of Business" /> 
<ListView android:id="@+id/suggestionList" 
    android:layout_width="fill_parent" android:layout_height="wrap_content"> 
</ListView> 

이 ListView에 사용자를 표시해야합니다. 모든 키 업 이벤트 해고 현재에, 나는 새로운 AsyncTask를 이런 식으로 부르고 ...

 EditText txtBusinessName = (EditText) findViewById(R.id.txtBusinessName); 
       txtBusinessName.setOnKeyListener(new View.OnKeyListener() { 
        @Override 
        public boolean onKey(View v, int keyCode, KeyEvent event) { 
         if (event.getAction() == KeyEvent.ACTION_UP) { 
          if (v instanceof EditText) { 
           EditText txtBusinessName = ((EditText) v); 

           if (txtBusinessName.length() > 0) { 
            if (suggestionTask != null) { 
            suggestionTask.cancel(true); 
            suggestionTask = null; 
            } 
            suggestionTask = new GetCompaniesByKeywordAsyncTask(
             AddBusinessActivity.this, s); 
            suggestionTask.execute(txtBusinessName.getText() 
             .toString()); 
           } 
          } 
         } 
         return false; 
        } 
       }); 

는 방법은 그냥 AsyncTask를의 단일 인스턴스를하고있는 사용자 유형과 이름을 검색하도록 요청 있는가 EditText? 너무 많은 AsyncTask를 만드는 것은 효율적이지 않으며 결국 예외로 끝날 것입니다. 이름을 수신하면 ListView를 채 웁니다. ListView에 내용을 기반으로 크기를 다시 지정하도록 요청할 수 있습니까?

답변

2

단일 AsyncTask를 만들려면 AsyncTask를 다시 구성하여 요청 큐를 기반으로 실행해야합니다. 대기열에 처리하려는 모든 키워드가 포함되어 있습니다. 그런 다음이 AsyncTask를 리스너 외부에서 한 번 실행하고 OnKeylistener에서 키워드를 추가합니다.

리스트 뷰를 업데이트하려면, 우리는 doInBackground

코드가 rougly에 수정 수정 AsyncTask를 다음


    @Override 
    protected Integer doInBackground(Void... params) { 
     int errorCode = 0; 

     try { 
      // while running in the context of your activity 
      // you should set this boolean to false once you have leave the activity 
      while(!isRunning){ 
       // blocking call to get the next keyword that is added to the queue 
       String responseData = getNextKeyword(); 

       // once you get the next keyword, you publish the progress 
       // this would be executed in the UI Thread and basically would update the ListView 
       publishProgress(responseData); 
      } 
     } catch(Exception e) { 
      // error handling code that assigns appropriate error code 
     } 

     return errorCode; 

    } 

    @Override 
    protected void onPostExecute(Integer errorCode) { 
     // handle error on UI Thread based on errorCode 
    } 

    @Override 
    protected void onProgressUpdate(String... values) { 
     String searchKeyword = values[0]; 

     // handle the searchKeyword here by updating the listView 
    } 

    /*** 
    * Stub code for illustration only 
    * Get the next keyword from the queue 
    * @return The next keyword in the BlockingQueue 
    */ 
    private String getNextKeyword() { 
     return null; 
    } 

    /*** 
    * Stub code for illustration only 
    * Add new keyword to the queue, this is called from the onKey method 
    * @param keyword 
    */ 
    public void addKeyword(String keyword) { 
     // add the keyword to the queue 
    } 

의 골격 코드의 결과에 따라 ListView에 업데이트됩니다 그 onProgressUpdate을 사용합니다 :


// instantiate AsyncTask once 
suggestionTask = new GetCompaniesByKeywordAsyncTask(
     AddBusinessActivity.this, s); 

// run only one AsyncTask that is waiting for any keyword in the queue 
suggestionTask.execute(); 

EditText txtBusinessName = (EditText) findViewById(R.id.txtBusinessName); 
txtBusinessName.setOnKeyListener(new View.OnKeyListener() { 
    @Override 
    public boolean onKey(View v, int keyCode, KeyEvent event) { 
     if (event.getAction() == KeyEvent.ACTION_UP) { 
      if (v instanceof EditText) { 
       EditText txtBusinessName = ((EditText) v); 

       if (txtBusinessName.length() > 0) { 
        // add new keyword to the queue for processing 
        suggestionTask.addKeyword(txtBusinessName.getText() 
         .toString()); 
       } 
      } 
     } 
     return false; 
    } 
}); 
+0

AsyncTask 개체에서 큐 컬렉션을 유지 관리해야합니까? – Neutralizer

+0

AsyncTask 개체 외부에서 큐를 사용하지 않으려는 경우 AsyncTask의 인스턴스 변수로 유지하는 것이 좋습니다. 대기열의 경우 [BlockingQueue] (http://developer.android.com/reference/java/util/concurrent/BlockingQueue.html)를 활용 해보십시오. – momo

+0

잘 했어. ListView가 채워지면 알 수 있습니까? 어떻게 내용을 기준으로 크기를 조정할 수 있습니까? – Neutralizer

관련 문제