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
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 call notifyDataSetChanged(). If set to false, caller must manually call notifyDataSetChanged() to have the changes reflected in the attached view. The default is true, and calling notifyDataSetChanged() 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) {
}
});
As per my understanding. You are notifying the adapter inside onItemSelected(). In case of Spinner adapter initialization onItemSelected() will get called once for first time . So the list you will get in Spinner is always the new one(i.e 2006-2010) never the first one(i.e 2013-2017).
So if you do notify adapter on some other action or maybe avoid the first call to onItemSelected() your code will work fine .
Related
anybody can help! the spinner listener doesn't work by this fragment.
it's never called
I have tried to implement an AdapterView.OnItemSelectedListener
I try to implement the spinner in Fragment I don't know if that really matter
Java code
'''
Spinner mSpinner = (Spinner) view.findViewById(R.id.usernameSpinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_spinner_item, users);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner.setAdapter(adapter);
mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "onItemSelected: " + position);
//its never called
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
'''
Is there a way to change the displayed list inside of the Spinner after selection. I have 2 Strings, English and Finnish and I want to first change their language when one is selected, secondly change their order when the other is selected.
private void initLanguageSpinner() {
List<String> spinnerLocale = new ArrayList<>();
if ((currentdocumentLocale.toString().startsWith("deviceNameFi") || currentdocumentLocale.getLanguage().equals("fi"))) {
spinnerLocale.add(getLocalizedResources(context, currentdocumentLocale).getString(R.string.finnish_language));
spinnerLocale.add(getLocalizedResources(context, currentdocumentLocale).getString(R.string.english_language));
} else {
spinnerLocale.add(getLocalizedResources(context, currentdocumentLocale).getString(R.string.english_language));
spinnerLocale.add(getLocalizedResources(context, currentdocumentLocale).getString(R.string.finnish_language));
}
ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(), R.layout.document_spinner_item, spinnerLocale);
adapter.setDropDownViewResource(R.layout.document_spinner_dropdown_item);
customerSelectedLanguageSpinner.setAdapter(adapter);
customerSelectedLanguageSpinner.setSelection(0, false);
customerSelectedLanguageSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (customerSelectedLanguageSpinner.getSelectedItem().toString().equals(getLocalizedResources(context, currentdocumentLocale).getString(R.string.finnish_language))) {
onLocaleChangedFi();
initLanguageSpinner();
} else if (customerSelectedLanguageSpinner.getSelectedItem().toString().equals(getLocalizedResources(context, currentdocumentLocale).getString(R.string.english_language))) {
onLocaleChangedEng();
initLanguageSpinner();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
By doing this it basically does what I need, but it also goes into an endless loop since the onItemSelected is always called after initialization, even when I do the .setSelection(0, false). Is there a way to do what I need?
EDIT
So I tried creating a new adapter and then notifying it of changes.
private ArrayAdapter<String> spinnerAdapter;
private void initLanguageSpinner() {
List<String> spinnerLocale = new ArrayList<>();
if ((currentdocumentLocale.toString().startsWith("deviceNameFi") || currentdocumentLocale.getLanguage().equals("fi"))) {
spinnerLocale.add(getLocalizedResources(context, currentdocumentLocale).getString(R.string.finnish_language));
spinnerLocale.add(getLocalizedResources(context, currentdocumentLocale).getString(R.string.english_language));
} else {
spinnerLocale.add(getLocalizedResources(context, currentdocumentLocale).getString(R.string.english_language));
spinnerLocale.add(getLocalizedResources(context, currentdocumentLocale).getString(R.string.finnish_language));
}
spinnerAdapter = new ArrayAdapter<>(getActivity(), R.layout.document_spinner_item, spinnerLocale);
spinnerAdapter.setDropDownViewResource(R.layout.document_spinner_dropdown_item);
customerSelectedLanguageSpinner.setAdapter(spinnerAdapter);
customerSelectedLanguageSpinner.setSelection(0, false);
customerSelectedLanguageSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (customerSelectedLanguageSpinner.getSelectedItem().toString().equals(getLocalizedResources(context, currentdocumentLocale).getString(R.string.finnish_language))) {
setSpinnerAdapter(customerSelectedLanguageSpinner.getSelectedItem().toString());
onLocaleChangedFi();
} else if (customerSelectedLanguageSpinner.getSelectedItem().toString().equals(getLocalizedResources(context, currentdocumentLocale).getString(R.string.english_language))) {
setSpinnerAdapter(customerSelectedLanguageSpinner.getSelectedItem().toString());
onLocaleChangedEng();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
private void setSpinnerAdapter(String language){
if(language.equals("fi")){
String[] myListFinnish = new String[] { getLocalizedResources(context, currentdocumentLocale).getString(R.string.finnish_language), getLocalizedResources(context, currentdocumentLocale).getString(R.string.english_language)};
spinnerAdapter = new ArrayAdapter<>(getActivity(), R.layout.document_spinner_item, myListFinnish);
} else {
String[] myListEnglish = new String[] { getLocalizedResources(context, currentdocumentLocale).getString(R.string.english_language), getLocalizedResources(context, currentDocumentLocale).getString(R.string.finnish_language)};
spinnerAdapter = new ArrayAdapter<>(getActivity(), R.layout.document_spinner_item, myListEnglish);
}
spinnerAdapter.setDropDownViewResource(R.layout.document_spinner_dropdown_item);
spinnerAdapter.notifyDataSetChanged();
}
This way it does not even change the list strings or order. onLocaleChangedEng(); basically changes the Locale variable in the application.
your code is a dead loop. and if the adapter item data changed,
such as add, remove, clear by adapter you can use notifyDataSetChanged
method.
Notifies the attached observers that the underlying data has been changed and any View reflecting the data set should refresh itself.
adapter.clear()/add(object)/addAll();
adapter.notifyDataSetChanged();
then the view will update but not init.
if the whole data changed, you can also recreate an adapter, and then set data
dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, newStringList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerCategory.setAdapter(dataAdapter)
At the same time, you can also clear and addAll, then notifyDataSetChanged
adapter.clear() //remove all data;
adapter.addAll(source);
adapter.notifyDataSetChanged();
//or remove it, then insert it in the first. that is acturl for your conditon
adapter.remove(objcet) //remove special data;
adapter.insert(object,index);
adapter.notifyDataSetChanged();
Secondly, you can also set a Tag to make when init the onItemSelected not called. the code like this:
//define a tag when first it is 0
int check = 0;
//then in the onItemSelected add a check condition
public void onItemSelected(AdapterView<?> parent, View arg1, int pos,long id) {
if(++check> 1) {
//do some things when item selected.
}
}
use notifyDataSetChanged to update data, not every time init spinner. if you only want to remove the init selected effect, use the check tag.
I am new in android ,I want work like, In Spinner if i select any other items form array,that item should get selected including with some text,For example,if My spinner having 10 items,if i select 6th item that item should display like "Your Item Is: Item6",This should be display in my spinner as first item,After select of items form the array,Please help me ,,Thanks in advance..
String[] categories = {"Select one","Automobile","Computers","Education"};
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
then onItemSelected Listerner Do :-
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
String item = parent.getItemAtPosition(position).toString();
categories[0] = item;
ArrayAdapter<String> newdataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
spinner.setAdapter(newdataAdapter);
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
ArrayAdapter arrayAdapter = null;
String[] list=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//you can replace the below list with your list
list = {"Mercury","Venus","Earth","Mars","Jupiter","Saturn","Uranus","Neptune","Pluto"};
final Spinner spinner = (Spinner) findViewById(R.id.spinner);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinner.setAdapter(arrayAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
spinner.setPrompt("Your selected item is:"+list[position]);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
I have two spinners in an Activity where the second Spinner's selection set is based on what the user picked for the first Spinner. I use a private class variable in the Activity which is set in the top Spinner's OnItemSelectedListener and then referenced in the bottom Spinner's OnItemSelectedListener to obtain the correct selection set.
This almost always works, but sometimes (mainly when app was run, not exited, and then started again by a user click some long time later) I get a null pointer exception in the second Spinner's OnItemSelectedListener due to this local variable not being set. This indicates to me that after the OnCreate that the second Spinner's OnItemSelectedListener was called before the first Spinner's.
Is there any method to force a certain order in the listeners being fired or is there a better design approach to handle this second Spinner's dependency on the first Spinner?
Example code:
package com.crashtestdummylimited.navydecoder;
public class Test extends Activity {
// Variable that at times is still null
private ReferenceData referenceData;
private void setupSpinnerFromArray (int spinnerId, String stringArray[], OnItemSelectedListener listener) {
Spinner spinner = (Spinner) findViewById(spinnerId);
ArrayAdapter <CharSequence> adapter = new ArrayAdapter <CharSequence>(
this, android.R.layout.simple_spinner_item, stringArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(listener);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_screen);
// Setup Top (main) Spinner
Spinner spinner1 = (Spinner) findViewById(R.id.mainDecodeSpinner);
ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(
this, R.array.level0_list_array, android.R.layout.simple_spinner_item);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter1);
spinner1.setOnItemSelectedListener(new MainDecoderItemSelectedListener());
// Setup Bottom (dependent) Spinner
setupSpinnerFromArray(R.id.secondaryDecodeSpinner, R.array.level1_list_array, new SecondaryDecoderItemSelectedListener());
}
public class MainDecoderItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
String selectedString = parent.getItemAtPosition(pos).toString();
if (selectedString.equals("AAA")){
// Problem variable is set
referenceData = new RatingCodes();
setupSpinnerFromArray(R.id.secondaryDecodeSpinner, referenceData.getKeys(), new SecondaryDecoderItemSelectedListener());
}
else if (selectedString.equals("BBB")){
// Problem variable is set
referenceData = new IMSCodes();
setupSpinnerFromArray(R.id.secondaryDecodeSpinner, referenceData.getKeys(), new SecondaryDecoderItemSelectedListener());
}
// TODO: Improve what occurs if no match which should not occur
}
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing.
}
}
public class SecondaryDecoderItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
String key = parent.getItemAtPosition(pos).toString();
// **** referenceData being null at this point has caused crashed ****
String value = referenceData.getValue(key);
// ... Update text on activity screen ...
}
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing.
}
}
}
public void onItemSelected(AdapterView<?> parent,View view, int pos, long id)
{
if(pos == 0)
{ //when it loads on onCreate() then pos is always 0
//donothing
}
else
{ //If user manually select item
//do what you need to do on manual user selection
}
}
I wanted to display my data into android spinner from database.
I used two spinner..
2nd spinner should reflect once 1st spinner item is selected, every thing is working fine..data is loaded into the second spinner, but not displaying into 2nd spinner when 2nd spinner item is selected.
Spinner1 = (Spinner)findViewById(R.id.createProfileCitySpinnerId);
Spinner2 = (Spinner)findViewById(R.id.createProfileStateSpinnerId);
//for 1st spinner.....(working)
final List<String> list1 = new ArrayList<String>();
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item,list1);
Spinner1.setAdapter(adapter1);
//for second spinner...
final List<String> list2 = new ArrayList<String>();
Spinner1.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id)
{
if(//some condition using id)
{
list2.add(stateCursor.getString(1));
}
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
}
});
//everything is working data is loading, but not display once item is selected on 2nd spinner
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,list2);
stateSpinner.setAdapter(adapter2);
You need to add the element directly to the adapter (not to list2), the ArrayAdapter keeps its own internal data. Try this code on your onItemSelected:
adapter2.add(stateCursor.getString(1));
adapter2.notifyDataSetChanged();
Call adapter2.notifyDataSetChanged();
such as
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id)
{
if(//some condition using id)
{
list2.add(stateCursor.getString(1));
adapter2.notifyDataSetChanged();
}
}
see http://developer.android.com/reference/android/widget/ArrayAdapter.html for more information.
public void notifyDataSetChanged () Since: API Level 1
Notifies the attached observers that the underlying data has been
changed and any View reflecting the data set should refresh itself.