Tima
Tima

Reputation: 12915

notifyDataSetChanged doesn't work?

I write following application:

I took TextChangedListener to update this last list item. But it seems, that update occurs only once.

I add a bit code of me. May be somebody can show me, what did i do wrong.

public class HelloListView extends Activity 
{
    List<String> countryList = null;    
    AutoCompleteTextView textView = null;   
    ArrayAdapter adapter = null;

    static String[] COUNTRIES = new String[] 
    {
          "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra",
          "Yemen", "Yugoslavia", "Zambia", "Zimbabwe", ""
    };

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);        

        countryList = Arrays.asList(COUNTRIES);

        textView = (AutoCompleteTextView) findViewById(R.id.edit);
        adapter = new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, countryList);
        adapter.notifyDataSetChanged();        
        textView.setAdapter(adapter);
        textView.setThreshold(1);

        textView.addTextChangedListener(new TextWatcher() 
        {

            public void onTextChanged(CharSequence s, int start, int before, int count) 
            {               
                countryList.set(countryList.size()-1, "User input:" + textView.getText());                
            }

            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) 
            {               
            }

            public void afterTextChanged(Editable s) 
            {
            }
        });

        new Thread() 
        {
            public void run() 
            {
                // Do a bunch of slow network stuff.
                update();
            }
        }.start();        
    }

    private void update() 
    {
        runOnUiThread(new Runnable() 
        {
            public void run() 
            {
                adapter.notifyDataSetChanged();
            }
        });
    }
}

Upvotes: 2

Views: 9053

Answers (2)

jowett
jowett

Reputation: 764

In the function onTextChanged(), create a new adapter and attach it, then it'll work:

countryList.set(countryList.size()-1, "User input:" + textView.getText());      
adapter = new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, countryList);
textView.setAdapter(adapter);

Seems it isn't a perfect one, but it works!

Upvotes: 2

CommonsWare
CommonsWare

Reputation: 1007296

Do not modify the ArrayList. Modify the ArrayAdapter, using add(), insert(), and remove(). You do not need to worry about notifyDataSetChanged().

Also, I agree with Mayra -- consider using AsyncTask instead of your thread and runOnUiThread() combination.

Upvotes: 12

Related Questions