SharePrefs not working for Android Spinner - behaviour very erratic - android

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();

Related

How can I save data from an EditText component so it shows up when the app is reopened?

I am using Android Studio and programming in Kotlin. I haven't been able to find a way to save the data entered by the user so it appears when they reopen the app. Thank you ahead of time!
You have to store your data in shared preference when any click event listen or on edittext textwatcher you can set your character in preference but best way is on any click event save data on preference and when activity open set data from preference on edittext.
Store it in Shared Preferences
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
use this save the value..
Editor editor = sharedpreferences.edit();
editor.putString("key_name", "value"); //here give name and value to save
editor.commit();
use this to get the value.
String edittextvalue = pref.getString("key_name", null); //put edittextvalue where ever you what to show the value.
use this step to remove or clear the value
editor.remove("name");
editor.commit();

Android Google Fit select max results

I try to develop some fitness application which will use Google Fit.
And i have one question. Assume that user make some sport activity a few days in a week. And want to show him his best result. The only way I know I can do this - is load all data from user history and then select the set with maximum value.
And its obvious that I dont like that method because of the fact that I should load all the history. (And the user can have history for a few years).
Another way is to store data in local database (so i dont need to load all history every time the user want to see his best result) and synch it with google fit data, but I think its too dificult.
Do we have some other options for that kind of tasks?
Use sharedpreferences to save the value,
To set value
SharedPreferences prefs = this.getSharedPreferences("myhighestscore", Context.MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putInt("key", score);
editor.commit();
To get value
SharedPreferences prefs = this.getSharedPreferences("myhighestscore", Context.MODE_PRIVATE);
int score = prefs.getInt("key", 0);
here is a link.
Using Shared Preferences

How do I save the progress already made in an app?

I'm doing a quiz where the user unlocked the levels, but when he closes the app all progress is lost, and he has to redo everything again. How can I fix this and make the user's progress automatically saved? Or with it by clicking a button, I do not know
You can save it in SharedPreferences and check the value of it every time application is opened.
To save value:
SharedPreferences sp = getSharedPreferences("YourFileName", Context.MODE_PRIVATE); //YourFileName= Any file name you give it
SharedPreferences.Editor editor = sp.edit();
editor.putString("levels", your_level_value); //levels=key at which data is stored, your_level_value=No. of levels completed
editor.apply();
To retrieve value:
SharedPreferences sp = getSharedPreferences("YourFileName", Context.MODE_PRIVATE); //YourFileName= Any file name you give it
String levelCompleted = sp.getString("levels", "0"); //levels=key at which no. of levels is saved.

how to save multiple data in shared preferences in android

my app contains a list of dates in which there is toggle button
1.>on check it sets alarm and on uncheck it deletes the alarm
these is working normally but when i close aplication then alarm will automaically gets deleted
so i want to save data in shared preferences when toggle button is clicked and delete particular data when btn is unchek from shared preferneces for this i am doing
SharedPreferences sharedPref = context.getSharedPreferences("com.example.dd.mydata", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("alarm"+cday+"_"+month,cday);
editor.commit();
where cday and month is alarm date and month
on recieve i have to fetch these data and match with date so that alarm can ring
so on recive i am doing this
SharedPreferences sharedPref = arg0.getSharedPreferences("com.example.dd.mydata", Context.MODE_PRIVATE);
String name = sharedPref.getString("alarm"+cday+"_"+cmonth, null);
in these way i am achiving the value of shared preferences in both class but it is working for single toggle button clicking more than 2 button **overrites the also tell me how can i check whether the current dates exists or not in shared prefernces
You can call SharedPreferences.contains(String key) method.
For example, contains("alarm"+cday+"_"+cmonth)

Start a specific part of an application only one time after installation

On my app I've got a Database which i have to fill one time with some entries. I have packed this step in my splashscreen. Now I got the problem every time i open up my application it puts again all entries to my database.
I'm looking for a way to let this happen only on the really first time the app gets opend. But i don't find out, how i can realize this.
I'm happy over every input and Idea!
Have a nice day
safari
Notes
I had an idea to realize that. I make a boolean in my SplashScreen, which takes a look at the database table if there is nothin, it inputs all the entries and makes a mark in a table that its filled like yes.
Afterwards if i open the app again it takes a look at the database if theres a yes or what ever i definied, it doesn't put again all entries in my database.
Sorry for that crappy definition of what my idea is, my english isnt the best.
I'm searching for an easier way than this.
why not have a startup activity that checks if the app is launched for the first time ( and stores the value in the app preferences ) and either forwards to the database setup activity or to the main activity....
Here's a sample on how to read and write to the preferences:
Define preference key:
public static final String KEY_APP_IS_INITIALIZED = "APP_INITIALIZED";
read boolean value from preferences:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context)
boolean appIsInitialized = prefs.getBoolean(KEY_APP_IS_INITIALIZED, false);
store boolean value to preferences:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context)
Editor editor = prefs.edit();
editor.putBoolean(KEY_APP_IS_INITIALIZED, true);
editor.commit();
Launching the activities:
Intent intent = new Intent(startup_activity,
db_initialized ?
MainActivity.class :
DbInitActivity.class);
startup_activity.startActivity(intent);
You could use SharedPreferences to store a boolean value which indicates if the database is already filled.
You can store the data using this code:
SharedPreferences pref = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean(key, value);
editor.commit();
and then when you start the application you just read your value using:
SharedPreferences pref = getPreferences(MODE_PRIVATE);
pref.getBoolean(value, false);
// Check if DB is set up on start
SharedPreferences settings = getSharedPreferences("yourappidentifiername",MODE_PRIVATE);
String DbSetUp = settings.getString("dbsetup", "no");
// DbSetUp is "no" or "yes"
// Set that DB is set up
SharedPreferences settings = getSharedPreferences("yourappidentifiername",MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("dbsetup", "yes");
editor.commit();
Not an optimal solution, but you could check for one of your entries, if they don't exist, add them to your DB, otherwise ignore them.
Try this....
Have one bool value in shared preferences.
Check that variable is set or not on each start of the application.
if not set then set it and perform db operation.
if set don't do db operation just go to next steps.
I've got an idea, reading other answers.
Use a version for the database to write in the sharedpreference, so next time you'll need to update the database, just delete the old one and refill the new one with you data.
public void populateResDB(int version){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
int resDbVersion = prefs.getInt("ResDBVersion", 1);
if(resDbVersion<version){
//Populate database here
//Delete table/db
//Populate the table/database with new or updated data
//Update ResDBVersion for the next time
Editor editor = prefs.edit();
editor.putInt("ResDBVersion", version);
editor.commit();
}else{
//installed db has the same version as the one we want to install
//so, do nothing.
}
}
I'm trying it now, not yet tested.
In the onCreate of the splash activity use:
populateResDB(1); //1 is for the first time, increase it manually
You can use method onCreate in your database helper - it's used only, when new database is created, so I think that is what you're looking for.

Categories

Resources