'SharePrefs not working for Android Spinner - behaviour very erratic
I have a spinner inside of a dialog box, which you can use to select a currency for my app. When you select a currency, it connects to an api from a currency site and displays the parsed info using Json to display the chosen currency's info in my app's mainactivity.
I have used shared preferences to save the index no of the selected spinner choice and have some coding at the beginning of the oncreate method to retrieve the saved spinner index no when the activity is started back up, which will then also apply the currency associated with the index by using the site's api and json again.
The shared preferences file seems to update with the selected index no when I go into it to check, but upon starting the activity it will show the right currency, before very quickly changing to one of the others. The behaviour in retrieving and applying the right index no from shared prefs seems very erratic. Is anybody able to take a look and advise where I might be going wrong please?
An example of the code for when the spinner is used is:
if (newIndex == 1) {
// save inputted spinner position to sharedpreferences
int userChoice = powerSpinnerView.getSelectedIndex();
SharedPreferences sharedPref =
getSharedPreferences("MySharedPref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.clear();
editor.putInt("UserChoice", userChoice);
editor.apply();
Toast.makeText(getApplicationContext(),"CURRENCY CHANGED TO GBP",Toast.LENGTH_SHORT).show();
The code for applying shared prefs upon start up:
// Retrieve spinner position from sharedpreferences
SharedPreferences sharedPref = getSharedPreferences("MySharedPref",
Context.MODE_PRIVATE);
int spinnerValue = sharedPref.getInt("UserChoice", -1);
if (spinnerValue != 1){
// set the value of the spinner
Toast.makeText(getApplicationContext(),"GBP
SELECTED",Toast.LENGTH_SHORT).show();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|