Issue
I am trying to update the spinner view by calling notifyDataSetChanged()
. But its not updating.
The below is my Activity:
public class DisplayArchive2 extends AppCompatActivity {
List<String> yearslist;
Spinner spinner;
ArrayAdapter<String> dataAdapter;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.archive2);
spinner = (Spinner) findViewById(R.id.year_spinner);
yearslist = new ArrayList<String>();
yearslist.add("2017");
yearslist.add("2016");
yearslist.add("2015");
yearslist.add("2014");
yearslist.add("2013");
dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,yearslist);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
yearslist.clear();
yearslist.add("2010");
yearslist.add("2009");
yearslist.add("2008");
yearslist.add("2007");
yearslist.add("2006");
dataAdapter.notifyDataSetChanged();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
The list of years is not changing on selecting any year.
It looks like below
Solution
Try this use dataAdapter2.setNotifyOnChange(true);
its working fine i have tested it my device
void setNotifyOnChange (boolean notifyOnChange)
Control whether methods that change the
list (add(T)
,addAll(Collection)
,addAll(Object[])
,insert(T, int)
,remove(T)
,clear()
,sort(Comparator))
automatically callnotifyDataSetChanged()
. If set to false, caller must manually callnotifyDataSetChanged()
to have the changes reflected in the attached view. The default is true, and callingnotifyDataSetChanged()
resets the flag to true.
CODE
List<String> yearslist;
Spinner spinner;
ArrayAdapter<String> dataAdapter2;
spinner = (Spinner) findViewById(R.id.year_spinner);
yearslist = new ArrayList<String>();
yearslist.add("2017");
yearslist.add("2016");
yearslist.add("2015");
yearslist.add("2014");
yearslist.add("2013");
dataAdapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,yearslist);
dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter2);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (position == 0) {
} else {
yearslist.clear();
yearslist.add("2010");
yearslist.add("2009");
yearslist.add("2008");
yearslist.add("2007");
yearslist.add("2006");
dataAdapter2.setNotifyOnChange(true);
dataAdapter2.notifyDataSetChanged();
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Answered By - AskNilesh