How to make a spinner show previously selected item after refresh? - android

What I have is a Settings activity on which I choose the language via spinner. When I change it to Russian for example the language changes, but when I open the Settings menu again the selected item on the spinner is the first item (English) and not the current one (Russian).
This is my spinner
Resources res = getResources();
language = res.getStringArray(R.array.languages_arrays);
Spinner spinner = (Spinner) findViewById(R.id.toolbar_spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, R.layout.spinner_item_dropdown,
language);
spinner.setAdapter(adapter);
What do I need to change in the spinner in order to show the selected language?

If you want to set the previous selected item of a spinner you have to store the selected item and then set your selection :
here's an example wish i'am getting my previous selected item then fetching the item's position from he's array adapter
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String language = preferences.getString("language", "");
if(!language.equalsIgnoreCase(""))
{
int spinnerPosition = arrayAdapter.getPosition(language);
spinner.setSelection(spinnerPosition);
}
You can store your data as below :
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
SharedPreferences.Editor editor = preferences.edit();
editor.putString("language",spinner.getSelectedItem().toString(););
editor.apply();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});

For that u need to set spinner value programatically
for (int i=0 ;i<languages.length;i++)
{
if(languages[i] = "RUSSIAN")//change it according to ur prrefence
spinner.setSelection(i);
}

You have to save previous selected value somewhere in your app. When you open setting again check for that value and find position of it in array. Once you find location of it set Spinner selection to that position like below:
spinner.setSelection(position_of_selected_item);

Related

The right way to save spinner to sharepreferences

I have a spinner that have 3 values populated from array-list.
I want to save the spinner selected value to shared preferences so it can be loaded back again when the use comes back to the app. What is the correct way to do this (to avoid future problems)
1- Save position of the selection
2- Save the text of the selection
3- Get the position/text of the selection, get the corresponding enum, and save the enum name.
I am leaning towards the 3rd option incase the positions/texts changed in later updates but I am wondering what is the correct way of doing such task
Thank you
Save position (1 variant) and text (2 variant) are bad practice. Because text for your spinner items may will change in the future and their position can be changed.
I think, that you need to create enum or #TypeDef element and save it to sharedPreferences. #TypeDef is more performance but enum is more functionality (if you use Kotlin you can use sealed classes). For this solution just write mapper that can map enum to spinner item.
If you use enum, the best way is to save it name ENUM.name().
Read carefully and understand. Get the post and use at your own understanding.
Declare your spinner and sharedPreferences
public Spinner crimeType;
SharedPreferences sharedPreferencesFirstTime;
//////
sharedPreferencesFirstTime = getPreferences
(Context.MODE_PRIVATE);
String firstTime = getResources().getString(R.string.saved_first_time);
firstTimekey = sharedPreferencesFirstTime.getString
(getString(R.string.saved_first_time),
firstTime);
crimeType = v.findViewById(R.id.crimeType);
Initializing a String Array
String[] plants = new String[]{
"Antisocial behaviour",
"Arson",
"Burglary"
};
Initializing an ArrayAdapter
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<>(
getActivity(), android.R.layout.simple_spinner_item, plants
);
Sets the layout resource to create the drop down views.
/*
Parameters : resource
the layout resource defining the drop down views
*/
spinnerArrayAdapter.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);
Sets the Adapter used to provide the data which backs this
/*
setAdapter(SpinnerAdapter adapter)
Sets the Adapter used to provide the data which backs this Spinner.
*/
crimeType.setAdapter(spinnerArrayAdapter);
crimeType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//Get the text content
crime_string= parent.getItemAtPosition(position).toString();
//Get Position of the crime
selectionPosition=
parent.getItemAtPosition(position);
SharedPreferences.Editor editor = sharedPref.edit();
String key2 = crime_string;
editor.putString(getString(R.string.saved_login_key), key2);
editor.apply();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
//Another interface callback
}
});

Spinner, not set value if i dont click(android)

I have a spinner:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int childposition, long id) {
textView.setText(spinner.getSelectedItem().toString());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
textView.setText("");
}
});
Above you'll see that textView - is my text object. I'm displaying a text item spinner in the textView when I click it. If I dont click the spinner then my textView must be textView.setText("");
But the spinner is always set text in my textView, even if I do not choose spinner.
Question
How can I accomplish this?:
If I dont choose item spinner, textView is empty: textView.setText("");
If I do choose the item spinner, textView gets: textView.setText(spinner.getSelectedItem().toString());
String item = parent.getItemAtPosition(childposition).toString(); //Get selected item
if(item.equals("spinner")){ // Check if it equals spinner
textView.setText(item); // Set text to item
}else{
textView.setText(""); // If it doesn't equal spinner set text to ""
}
If I understood the question right, putting this instead of textView.setText(spinner.getSelectedItem().toString()); and deleting content of onNothingSelected should do the trick.
UPDATE
I finally understood what you mean. To do this create your spinner like this and add "" as first choice in your string-array resource :
String[] newArray = getResources().getStringArray(R.array.yourArray);
List<String> myResArrayList = Arrays.asList(newArray);
ArrayList<String> spinnerItems = new ArrayList<String>(myResArrayList);
//Making adapter with ArrayList instead of String[] allows us to add/remove items later in the code
Spinner spinner = (Spinner) findViewById(R.id.spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, spinnerItems);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
spinnerItems.remove(0);
adapter.notifyDataSetChanged(); // Here we remove the first choice which is "" so the user won't be able to select empty.

How to save state of spinner using Java Android

I am trying to save the state of a spinner select. So if I select a choice in the spinner and move into a different activity, then coming back to the activity with the spinner that choice should still be selected. I found some tutorials but the ones of I have tried are deprecated.
Here's my spinner:
//language selection list
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.language_list, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// storing string resources into Array
lang_list = getResources().getStringArray(R.array.language_list);
Toast.makeText(getBaseContext(), "You have selected : " + lang_list[index],
Toast.LENGTH_SHORT).show();
choice = spinner.getSelectedItem().toString();
final ImageView country_flag = (ImageView)findViewById(R.id.country);
String s=((TextView)arg1).getText().toString();
if(s.equals("English"))
country_flag.setImageDrawable(getResources().getDrawable(R.drawable.eng_spinner));
if(s.equals("German"))
country_flag.setImageDrawable(getResources().getDrawable(R.drawable.german_spinner));
if(s.equals("French"))
country_flag.setImageDrawable(getResources().getDrawable(R.drawable.french_spinner));
if(s.equals("Spanish"))
country_flag.setImageDrawable(getResources().getDrawable(R.drawable.spanish_spinner));
}
Save the current spinner's state on onSaveInstanceState() by putting the date, time, etc. into the bundle with a key by getting the index of the spinner's current selected position. Afterwards, on your onCreate(), check if bundle == null, and if it is not null (which it shouldn't be if your activity was recreated due to resume), you retrieve the values you stored in it with the keys. Finally, manually set the values to your spinner using Spinner.setPosition() inside the onCreate().
http://developer.android.com/training/basics/activity-lifecycle/recreating.html
This should be a good read.

Spinner does not get selected after setting adapter

I have two spinner in dialog. Second one is dependent on first one. I want to bind it and then select it in edit mode. All works fine but second spinner does not get selected. However it get selected when I open my dialog next time.
Here is a part of my code.
ArrayAdapter<String> myAdap1 = (ArrayAdapter<String>) spnForeignKeyTable
.getAdapter();
int spinnerPosition1 = myAdap1.getPosition(objcolumn_schema
.getForeignKeyTable());
spnForeignKeyTable.setSelection(spinnerPosition1);
// Bind Column Spinner.Second spinner
dblist = DBAdapter.getColumns(pf.getString("dbid", ""),String.valueOf(objcolumn_schema.getForeignKeyTableID()));
ArrayAdapter<String> adpf = new ArrayAdapter<String>(
column.this, android.R.layout.simple_spinner_item,
dblist);
adpf.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnForeignKeyColumn.setAdapter(adpf);
int spinnerPosition2 = adpf.getPosition(objcolumn_schema.getForeignKey());
spnForeignKeyColumn.setSelection(spinnerPosition2);
for changing selected item in second spinner when first spinner selection change you will need to set setOnItemSelectedListener for first spinner as:
spinnerPosition1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> arg0, View v,
int position, long id)
{
// change second Spinner selection here
}
public void onNothingSelected(AdapterView<?> arg0)
{
//
}
});

Shared Preference & Spinner Not Maintaining State

I have a spinner like this:
// Spinner 1
final Spinner plan = (Spinner) dialog.findViewById(R.id.spinner1);
strings = getResources().getStringArray(R.array.paymentplan);
sAdapter = new SpinnerAdapter(this,
android.R.layout.simple_spinner_item, strings);
sAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
plan.setAdapter(sAdapter);
// plan.setAdapter(spinner1Adapter);
plan.setSelection(prefsDisplay.getInt("spinnerSelection1", 0));
plan.setOnItemSelectedListener(new MyOnItemSelectedListenerPlan());
When user clicks, I want it to save state:
public void onClick(View v) {
Editor editor2 = prefsPlan.edit();
int selectedPosition1 = plan.getSelectedItemPosition();
editor2.putInt("spinnerSelection1", selectedPosition1);
editor2.commit();
}
It saves the position in SharedPref, but the spinner goes back to default. Anyone see something here?
you are storing spinnerSelection
editor1.putInt("spinnerSelection", selectedPosition);
an accessing spinnerSelection1
prefsDisplay.getInt("spinnerSelection1", 0)
make them consistent.
Update
when you are accessing plan.getSelectedItemPosition(). then spinner is visible? I guess NO.
try to put a public variable for selected position. And update selected position in your MyOnItemSelectedListenerPlan. And then store that position in shared preferences. I guess it solve your problem.
to Save:
int selectedPosition = yourSpinner.getSelectedItemPosition()
editor.putInt("spinnerSelection", selectedPosition);
editor.commit();
to Load:
yourSpinner.setSelection(prefs.getInt("spinnerSelection",0));
if you are array used it should changed like this
String selectedString = yourArray[yourSpinner.getSelectedItemPosition()];
editor.putString("spinnerSelection", selectedString);
editor.commit();
checking array[i] against the value stored in prefs.if you use an
ArrayList instead this part could be done without the loop by calling
ArrayList.indexOf(prefs.getString("spinnerSelection", "");
when you commit show all above array item gone. show no one into
array.
Try below code and first save position of current selected item into one integer variable on onItemSelectedListener() using below code and after that store this variable value into shared preferences.
For Store value into one Variable.
int index;
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
// Here Position is Item Index
index = position;
}
For Store Value into shared preferences.
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putInt("SelectedIndex", index);
prefsEditor.commit();
And see below link for more information
Android Spinners
Android Shared Preferences
after saving to the preferences, you have to set the selected item to the spinner for further uses
as
int pos = prefsDisplay.getInt("spinnerSelection", "0");
display.setSelection(pos);
but you are using spinnerSelection1. so By default if there is no matching in the preferences. the default value will return. so Here 0 is returned and spinner is set to first position

Categories

Resources