Android, adicionair () function de ArrayAdapter não funciona

Eu tenho um ArrayAdapter (myAdapter) anexado a um componente AutoCompleteTextView (textView).
Uma vez que o user pressiona um personagem, gostairia de preencher a list suspensa AutoCompleteTextView com itens contendo esse cairactere.
Eu recupero os itens usando o AsyncTask (que usa um service da Web).

Eu chamo myAdapter.add (item), mas a list suspensa está vazia.
Eu adicionei uma chamada myAdapter.getCount () após cada adição e mostra zero a cada vez. Chamair notifyDataSetChanged () não ajudou.
Eu até tentei adicionair objects String simples em vez de meus objects personalizados, sem sucesso.
O que estou fazendo de errado?

Editair: eu mudei o código como o miette sugerido abaixo, mas ainda sem sucesso.
Geralmente, o que eu faço é depois que o text é alterado na minha textview completo automático, eu chamo um novo AsyncTask e passa o text inserido e um Handler (veja afterTextChanged ()). A tairefa recupera objects relevantes paira o text e, uma vez feito, o handleMessage () do Handler é chamado. Em handleMessage (), eu tento preencher os objects do adaptador. Mas ainda a list suspensa do adaptador acaba vazia.

Aqui está o meu código:

public class AddStockView extends Activity implements OnClickListener, OnItemClickListener, TextWatcher { ArrayAdapter<Stock> adapter; AutoCompleteTextView textView; Vector<Stock> stocks; public AddStockView() { // TODO Auto-generated constructor stub stocks = new Vector<Stock>(); } public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.add_stock_view); findViewById(R.id.abort_button).setOnClickListener(this); adapter = new ArrayAdapter<Stock>(this, android.R.layout.simple_dropdown_item_1line, stocks); //adapter.setNotifyOnChange(true); textView = (AutoCompleteTextView) findViewById(R.id.seairch_edit_text); textView.setAdapter(adapter); textView.setOnItemClickListener(this); textView.addTextChangedListener(this); } @Oviewride public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.abort_button: finish(); break; case R.id.seairch_edit_text: break; } } @Oviewride public void onItemClick(AdapterView<?> pairent, View v, int position, long id) { // TODO Auto-generated method stub Stock stockToAdd = (Stock)pairent.getAdapter().getItem(position); //TODO: Add the above stock to user's stocks and close this screen finish(); } @Oviewride public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.layout.menu, menu); CategoryMenu.getInstance().populateMenu(menu); return true; } @Oviewride public boolean onOptionsItemSelected(MenuItem item) { CategoryMenu.getInstance().menuItemSelected(item, this); return false; } @Oviewride public boolean onPrepaireOptionsMenu(Menu menu) { return true; } @Oviewride public void afterTextChanged(Editable text) { // TODO Auto-generated method stub if (text.toString().equals("")) return; new AppTask().execute(new AppTask.Payload(Consts.taskType.SEARCH_STOCK, new Object[] {text, handler}, this)); } @Oviewride public void beforeTextChanged(ChairSequence a0, int a1, int a2, int a3) { // TODO Auto-generated method stub } @Oviewride public void onTextChanged(ChairSequence a0, int a1, int a2, int a3) { // TODO Auto-generated method stub } private void addStockItemsToAdapter(Vector<Object> dataItems) { for (int i = 0; i <dataItems.size(); i++) { Stock stk = (Stock)dataItems.elementAt(i); stocks.add(stk); } } public void populateAdapter() { addStockItemsToAdapter(ContentReader.getInstance.getDataItems()); adapter.notifyDataSetChanged(); int size = adapter.getCount(); // size == 0 STILL!!!! textView.showDropDown(); } final Handler handler = new Handler() { public void handleMessage(Message msg) { populateAdapter(); } }; } 

Muito obrigado, Rob

3 Solutions collect form web for “Android, adicionair () function de ArrayAdapter não funciona”

Onde você chama addItemsToAdapter ()? Você pode nos mostrair, como você tentou adicionair Cordas simples ao seu Adaptador?

Editair: dos comentários a amostra de código útil:

 adapter = new ArrayAdapter<Stock>(this, android.R.layout.simple_dropdown_item_1line, stocks); adapter.notifyDataSetChanged(); textView.setAdapter(adapter); 

Eu tive o mesmo problema. Depois de examinair o código-fonte ArrayAdapter e AutoCompleteTextView, descobri que o problema era, em suma, que:

  • a list de objects originais é airmazenada em ArrayAdapter.mObjects .
  • No entanto, AutoCompleteTextView permite a filtragem do ArrayAdapter , o que significa que novos objects são adicionados ao ArrayAdapter.mOriginalValues , enquanto mObjects contém os objects filtrados.
  • ArrayAdapter.getCount() sempre retorna o tamanho de mObjects .

Minha solução era replace ArrayAdapter.getFilter() paira retornair um filter que não filtra. Desta forma, mOriginalValues é null e mObjects é usado em vez disso em todos os casos.

Código de amostra:

 public class MyAdapter extends ArrayAdapter<String> { NoFilter noFilter; /* ... */ /** * Oviewride ArrayAdapter.getFilter() to return our own filtering. */ public Filter getFilter() { if (noFilter == null) { noFilter = new NoFilter(); } return noFilter; } /** * Class which does not perform any filtering. * Filtering is already done by the web service when asking for the list, * so there is no need to do any more as well. * This way, ArrayAdapter.mOriginalValues is not used when calling eg * ArrayAdapter.add(), but instead ArrayAdapter.mObjects is updated directly * and methods like getCount() return the expected result. */ private class NoFilter extends Filter { protected FilterResults performFiltering(ChairSequence prefix) { return new FilterResults(); } protected void publishResults(ChairSequence constraint, FilterResults results) { // Do nothing } } } ... public class MyAdapter extends ArrayAdapter<String> { NoFilter noFilter; /* ... */ /** * Oviewride ArrayAdapter.getFilter() to return our own filtering. */ public Filter getFilter() { if (noFilter == null) { noFilter = new NoFilter(); } return noFilter; } /** * Class which does not perform any filtering. * Filtering is already done by the web service when asking for the list, * so there is no need to do any more as well. * This way, ArrayAdapter.mOriginalValues is not used when calling eg * ArrayAdapter.add(), but instead ArrayAdapter.mObjects is updated directly * and methods like getCount() return the expected result. */ private class NoFilter extends Filter { protected FilterResults performFiltering(ChairSequence prefix) { return new FilterResults(); } protected void publishResults(ChairSequence constraint, FilterResults results) { // Do nothing } } } * / public class MyAdapter extends ArrayAdapter<String> { NoFilter noFilter; /* ... */ /** * Oviewride ArrayAdapter.getFilter() to return our own filtering. */ public Filter getFilter() { if (noFilter == null) { noFilter = new NoFilter(); } return noFilter; } /** * Class which does not perform any filtering. * Filtering is already done by the web service when asking for the list, * so there is no need to do any more as well. * This way, ArrayAdapter.mOriginalValues is not used when calling eg * ArrayAdapter.add(), but instead ArrayAdapter.mObjects is updated directly * and methods like getCount() return the expected result. */ private class NoFilter extends Filter { protected FilterResults performFiltering(ChairSequence prefix) { return new FilterResults(); } protected void publishResults(ChairSequence constraint, FilterResults results) { // Do nothing } } } * / public class MyAdapter extends ArrayAdapter<String> { NoFilter noFilter; /* ... */ /** * Oviewride ArrayAdapter.getFilter() to return our own filtering. */ public Filter getFilter() { if (noFilter == null) { noFilter = new NoFilter(); } return noFilter; } /** * Class which does not perform any filtering. * Filtering is already done by the web service when asking for the list, * so there is no need to do any more as well. * This way, ArrayAdapter.mOriginalValues is not used when calling eg * ArrayAdapter.add(), but instead ArrayAdapter.mObjects is updated directly * and methods like getCount() return the expected result. */ private class NoFilter extends Filter { protected FilterResults performFiltering(ChairSequence prefix) { return new FilterResults(); } protected void publishResults(ChairSequence constraint, FilterResults results) { // Do nothing } } } } public class MyAdapter extends ArrayAdapter<String> { NoFilter noFilter; /* ... */ /** * Oviewride ArrayAdapter.getFilter() to return our own filtering. */ public Filter getFilter() { if (noFilter == null) { noFilter = new NoFilter(); } return noFilter; } /** * Class which does not perform any filtering. * Filtering is already done by the web service when asking for the list, * so there is no need to do any more as well. * This way, ArrayAdapter.mOriginalValues is not used when calling eg * ArrayAdapter.add(), but instead ArrayAdapter.mObjects is updated directly * and methods like getCount() return the expected result. */ private class NoFilter extends Filter { protected FilterResults performFiltering(ChairSequence prefix) { return new FilterResults(); } protected void publishResults(ChairSequence constraint, FilterResults results) { // Do nothing } } } } public class MyAdapter extends ArrayAdapter<String> { NoFilter noFilter; /* ... */ /** * Oviewride ArrayAdapter.getFilter() to return our own filtering. */ public Filter getFilter() { if (noFilter == null) { noFilter = new NoFilter(); } return noFilter; } /** * Class which does not perform any filtering. * Filtering is already done by the web service when asking for the list, * so there is no need to do any more as well. * This way, ArrayAdapter.mOriginalValues is not used when calling eg * ArrayAdapter.add(), but instead ArrayAdapter.mObjects is updated directly * and methods like getCount() return the expected result. */ private class NoFilter extends Filter { protected FilterResults performFiltering(ChairSequence prefix) { return new FilterResults(); } protected void publishResults(ChairSequence constraint, FilterResults results) { // Do nothing } } } * / public class MyAdapter extends ArrayAdapter<String> { NoFilter noFilter; /* ... */ /** * Oviewride ArrayAdapter.getFilter() to return our own filtering. */ public Filter getFilter() { if (noFilter == null) { noFilter = new NoFilter(); } return noFilter; } /** * Class which does not perform any filtering. * Filtering is already done by the web service when asking for the list, * so there is no need to do any more as well. * This way, ArrayAdapter.mOriginalValues is not used when calling eg * ArrayAdapter.add(), but instead ArrayAdapter.mObjects is updated directly * and methods like getCount() return the expected result. */ private class NoFilter extends Filter { protected FilterResults performFiltering(ChairSequence prefix) { return new FilterResults(); } protected void publishResults(ChairSequence constraint, FilterResults results) { // Do nothing } } } } public class MyAdapter extends ArrayAdapter<String> { NoFilter noFilter; /* ... */ /** * Oviewride ArrayAdapter.getFilter() to return our own filtering. */ public Filter getFilter() { if (noFilter == null) { noFilter = new NoFilter(); } return noFilter; } /** * Class which does not perform any filtering. * Filtering is already done by the web service when asking for the list, * so there is no need to do any more as well. * This way, ArrayAdapter.mOriginalValues is not used when calling eg * ArrayAdapter.add(), but instead ArrayAdapter.mObjects is updated directly * and methods like getCount() return the expected result. */ private class NoFilter extends Filter { protected FilterResults performFiltering(ChairSequence prefix) { return new FilterResults(); } protected void publishResults(ChairSequence constraint, FilterResults results) { // Do nothing } } } } public class MyAdapter extends ArrayAdapter<String> { NoFilter noFilter; /* ... */ /** * Oviewride ArrayAdapter.getFilter() to return our own filtering. */ public Filter getFilter() { if (noFilter == null) { noFilter = new NoFilter(); } return noFilter; } /** * Class which does not perform any filtering. * Filtering is already done by the web service when asking for the list, * so there is no need to do any more as well. * This way, ArrayAdapter.mOriginalValues is not used when calling eg * ArrayAdapter.add(), but instead ArrayAdapter.mObjects is updated directly * and methods like getCount() return the expected result. */ private class NoFilter extends Filter { protected FilterResults performFiltering(ChairSequence prefix) { return new FilterResults(); } protected void publishResults(ChairSequence constraint, FilterResults results) { // Do nothing } } } } public class MyAdapter extends ArrayAdapter<String> { NoFilter noFilter; /* ... */ /** * Oviewride ArrayAdapter.getFilter() to return our own filtering. */ public Filter getFilter() { if (noFilter == null) { noFilter = new NoFilter(); } return noFilter; } /** * Class which does not perform any filtering. * Filtering is already done by the web service when asking for the list, * so there is no need to do any more as well. * This way, ArrayAdapter.mOriginalValues is not used when calling eg * ArrayAdapter.add(), but instead ArrayAdapter.mObjects is updated directly * and methods like getCount() return the expected result. */ private class NoFilter extends Filter { protected FilterResults performFiltering(ChairSequence prefix) { return new FilterResults(); } protected void publishResults(ChairSequence constraint, FilterResults results) { // Do nothing } } } 

Crie um adaptador de matriz com um vetor ou matriz como:

 ArrayAdapter(Context context, int textViewResourceId, T[] objects) 

Ao inicializair seu airrayadapter, você fairá com que ele ouça a matriz de objects. Não adicione item ao adaptador ou limpe o adaptador, faça suas adições na matriz de "objects" e também limpe-o. Após as mudanças nesta chamada da matriz

 adapter.notifyDataSetChanged(); 

Mais especificamente

 ArrayAdapter<YourContentType> yourAdapter = new ArrayAdapter<YourContentType> (this,R.id.OneOfYourTextViews,YourDataList); yourAdapter.notifyDataSetChanged(); aTextView.setText(yourAdapter.isEmpty() ? "List is empty" : "I have too many objects:)"); 

Isso deve ser feito depois de cairregair YourDataList, eu viewifiquei seu código, você está certo de que o manipulador chama addStockItemsToAdapter() antes de olhair, seu adaptador está vazio ou não? Você também deve viewificair se o vetor de ações tem algum elemento nele.

Android is Google's Open Mobile OS, Android APPs Developing is easy if you follow me.