开发者

My adapter.notifyDataSetChanged() is not working

How to update an ArrayAdapter with my new array?

Belwo is my ArrayAdapter with a default array added to it.

String[] array_spinner = new String[]{"Select your state."};
ArrayAdapter<String> adapter = new ArrayAdapter<String> (this,android.R.layout.simple_spinner_item,array_spinner);
adapter.setDropDownViewResource(R.layout.state_spinner_layout);
Myspinner.setAdapter(adapter);

Now I load some开发者_开发知识库 JSON data that parses the info into the array_spinner_data and I want to call notifyDataSetChanged()

array_spinner = new String[]jsonArray.length(); 


        for (int i=0; i<jsonArray.length(); i++)
        {   
            String styleValue = jsonArray.getJSONArray(i).getString(0);    
            Log.d(TAG, styleValue);
            array_spinner[i] = styleValue;

        }
        Log.d(TAG, String.valueOf(array_spinner.length));
        adapter.notifyDataSetChanged();

I am not seeing any errors and all of my Log.d are coming back as they should. But when I click my spinner all that is showing is the original Select your state I left out some of the basic onCreate and Json load stuff but if anyone needs to see it just let me know.


notifyDataSetChanged is "not working" because you are not changing the data set, you are creating a new copy, one that the adapter has no knowledge about. Use a List<> instead of an array, and modify that same list object that you passed to your adapter and it will work. If you want to keep your current code, then you have to create a new adapter over the new data set and apply it to your spinner.


don't create a new list, clear the existing list then call notifydatasetchanged

someArrayList.clear();
someArrayList.add("element 1");
someArrayList.add("element 2");
yourAdapter.notifyDataSetChanged();


  • First create a list
  • Before reload the list every time with new value you have to clear the existing valuea
  • At last use your DataAdapter.notifyDatachanged(). function

    private Spinner spinnerTest;
    ArrayList<String> list_spinnerTest = new ArrayList<String>();
    
    list_spinnerTest.clear();
    
    String[] NameArray=new String []{"Load From Array","bbbbbbbb","cccccccccc","ddddddddd","eeeeeeeeee"};
    int count=5;
    for (int i = 0; i < count; i++) {
        list_spinnerTest.add(NameArray[i]);
    }
    ArrayAdapter<String> dataAdapterSpinner=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,list_spinnerTest);
    dataAdapterSpinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinnerTest.setAdapter(dataAdapterSpinner);
    
    dataAdapterSpinner.notifyDataSetChanged();
    
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜