2015-04-16 47 views
1

問題是我不能更新adapter設置後。對於第一個字符,它的工作正常,但如果我想改變它adapter繼續查看相同的建議。我如何更新adapter? 這是我的代碼。適配器從afterTextChanged更新()

public class UzActivity extends Activity { 

private static final String DEBUG_TAG = "HttpExample"; 
List<String> responseList; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_uz); 
    responseList = new ArrayList<String>(); 

    final String url = "http://booking.uz.gov.ua/purchase/station/"; 

    final AutoCompleteTextView textView = (AutoCompleteTextView) 
      findViewById(R.id.autoCompleteTextView1); 

    final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, 
      android.R.layout.simple_dropdown_item_1line, responseList); 


    textView.addTextChangedListener(new TextWatcher() { 
     @Override 
     public void beforeTextChanged(CharSequence s, int start, int count, int after) { 

     } 

     @Override 
     public void onTextChanged(CharSequence s, int start, int before, int count) { 

     } 

     @Override 
     public void afterTextChanged(Editable s) { 

      if (s.length()>0 && responseList.isEmpty()){ 

       try { 
        new FetchStationTask().execute(url + URLEncoder.encode(s.toString(), "UTF-8")); 
       } catch (UnsupportedEncodingException e) { 
        e.printStackTrace(); 
       } 
       textView.setAdapter(adapter); 
      } 

      else if(s.length()==0){ 
       responseList.clear(); 
      } 
     } 
    }); 
} 



private class FetchStationTask extends AsyncTask<String, Void, String>{ 

    @Override 
    protected String doInBackground(String... urls) { 
     try { 
      return new UzFetcher().getUrlString(urls[0]); 
     } catch (IOException e) { 
      return "Unable to retrieve web page. URL may be invalid."; 
     } 
    } 

    @Override 
    protected void onPostExecute(String result){ 

     try { 
      ObjectMapper objectMapper = new ObjectMapper(); 
      objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); 
      StationResponse st = objectMapper.readValue(result, StationResponse.class); 
      for (int i = 0; i<st.mStations.size(); i++){ 
        responseList.add(st.mStations.get(i).getTitle()); 
      } 


      Log.i(DEBUG_TAG, responseList.get(0)); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     Log.i(DEBUG_TAG, result); 

    } 
} 

回答

0

你試過notifyDataSetChangedadapter.notifyDataSetChanged()而不是textView.setAdapter(adapter)

也必須行if (s.length()>0 && responseList.isEmpty())但是當你把第一個數字可能適配器不爲空,也第二個條件if(s.length()==0)是假

+0

是的,我試過了,但它不工作。也許我應該在asynctask中設置adater? – lopoly

+0

你應該在'onPostExecute'中設置你的適配器,在'try..catch'下面用'notifyDataSetChanged'設置。你也可以使用過濾,如果它符合你的目的[(示例這裏)](http://stackoverflow.com/questions/5780289/filtering-listview-with-custom-object-adapter) – snachmsm

1
  • 請通知onPostExecute適配器(字符串結果){}方法。
onPostExecute(String result){ 
    adapter.notifyDataSetChanged(); 
}