How to save (switch) button state in android? - android

I am using SWITCH (like android toggle button ) instead of normal buttons in my andorid app.
The code works fine while enabling and disabling switches.
But i want to store the state of the switch.
Suppose i enable the switch and close my application the background code will run fine but the switch state will change to disabled.
Every time when i close the application the switch state becomes disabled.
Is there any way to store the switch State??

Use shared preferences or a database to store the state of your switch. It is essential that you depend on the lifecycle methods of Activity/fragment.
The following might help you:
#Override
public void onClick(View v)
{
if (toggle.isChecked())
{
SharedPreferences.Editor editor = getSharedPreferences("com.example.xyz", MODE_PRIVATE).edit();
editor.putBoolean("NameOfThingToSave", true);
editor.commit();
}
else
{
SharedPreferences.Editor editor = getSharedPreferences("com.example.xyz", MODE_PRIVATE).edit();
editor.putBoolean("NameOfThingToSave", false);
editor.commit();
}
}
The final nail:
#Override
protected void onCreate(Bundle savedInstanceState)
{
SharedPreferences sharedPrefs = getSharedPreferences("com.example.xyle", MODE_PRIVATE);
toggle.setChecked(sharedPrefs.getBoolean("NameOfThingToSave", true));
}
Edit:
The above code is working, however I feel it is a bad practice to get the shared preference values in onCreate, its better to make a loader class which inits your app variables well beforehand in a separate thread.
Update: Wed 24 Jul; 2019:
Android has view model support now - this can be used to handle switch state and persist it across sessions or configuration changes.

SharedPreferences pref = getSharedPreferences("save",MODE_PRIVATE);
unit.setChecked(pref.getBoolean("first", false));
if(isChecked) {
SharedPreferences.Editor editor = getSharedPreferences("save"MODE_PRIVATE).edit();
editor.putBoolean("first", true);
editor.apply();
unit.setChecked(true);}
else
{
SharedPreferences.Editor editor = getSharedPreferences("save",MODE_PRIVATE).edit();
editor.putBoolean("first",false);
editor.apply();
kilometer.setText("Km/h");
unit.setChecked(false);`enter code here`
}

Related

Android - Saving in Shared preferences stopped working

In my app I was using for more than 1 year "Shared preferences" to store some boolean values (if the user has seen the intro page for example). Now I added one more setting (if the user has seen the help page!) and all the settings stopped working...
I tried changing "commit" to "apply" with no luck. How could by just adding one more shared preference to make it stop working? Is there any properties limit?
My code:
public SharedPreferences getSettings() {
SharedPreferences settings = getSharedPreferences(AppConstants.PREFS_NAME, 0);
return settings;
}
old Activity for Intro:
private void saveUserHasSeenIntro() {
SharedPreferences.Editor editor = getSettings().edit();
editor.putBoolean(AppConstants.SETTING_BOOLEAN_HAS_SHOWN_INTRO_STEPS, true);
editor.commit();
}
where intro boolean is being read:
Boolean hasShownIntroSteps = getSettings().getBoolean(AppConstants.SETTING_BOOLEAN_HAS_SHOWN_INTRO_STEPS, false);
if ( !hasShownIntroSteps ) {
// show intro
} else {
New activity for help:
private void saveUserHasSeenHelp() {
SharedPreferences.Editor editor = getSettings().edit();
editor.putBoolean(AppConstants.SETTING_BOOLEAN_HAS_SHOWN_HELP_STEPS, true);
editor.commit();
}
where the "help" boolean is read:
Boolean hasSeenHelp = getSettings().getBoolean(AppConstants.SETTING_BOOLEAN_HAS_SHOWN_HELP_STEPS, false);
if ( !hasSeenHelp ) {
// show help activity
} else {
Your methods are fine and they should work perfectly. Check a couple of things just in case:
Ensure you don't call clear() or remove() method of the SharedPreferences editor after saving your prefs by mistake.
Ensure the constants AppConstants.SETTING_BOOLEAN_HAS_SHOWN_HELP_STEPS and AppConstants.SETTING_BOOLEAN_HAS_SHOWN_INTRO_STEPS have different values as the former could overlap the second by mistake.
Just add a breakpoint after setting the new pref and read the value to check if it's set just after it.
SharedPreferences.Editor editor = getSettings().edit();
editor.putBoolean(AppConstants.SETTING_BOOLEAN_HAS_SHOWN_HELP_STEPS, true);
editor.commit();
Boolean hasSeenHelp = getSettings().getBoolean(AppConstants.SETTING_BOOLEAN_HAS_SHOWN_HELP_STEPS, false);
In some extreme cases you could even implement SharedPreferences.OnSharedPreferenceChangeListener to see where your SharedPreferences are being changed to avoid unwanted pref sets.
It can be a Memory Limitation on your SharedPreferences file and usually this comes with an OutOfMemoryException. I guess if something like that would happen you would probably seen it in your code, unless you are not reading/writing in another Thread. How big is your SharedPreferences file in numbers of key - value pair ?

Save SWITCH button state, and recover state with SharedPrefs

I have a Settings class so the user can decide to subscribe/unsubscribe to channels in Parse Push.
I think I got it all figure out except for the part to recover, and maintain the switch state next time user open the app or changes the state.
Can someone please help me on how to save the state, and switch the SWITCH to what the user selected?
public class Settings extends Activity {
/**
* Called when the activity is first created.
*/
private Switch krspush, egspush;
public static final String PREFS_NAME = "SwitchButton";
krspush = (Switch) findViewById(R.id.krspush);
egspush = (Switch) findViewById(R.id.egspush);
SharedPreferences sharedPrefs = getSharedPreferences("SwitchButton", MODE_PRIVATE);
// How?
public void onKrsClick (View view) {
boolean on = ((Switch) view).isChecked();
if (on) {
SharedPreferences.Editor editor = getSharedPreferences("SwitchButton", MODE_PRIVATE).edit();
editor.putBoolean("onKrsClick", true);
editor.commit();
ParsePush.subscribeInBackground("egersund");
} else {
SharedPreferences.Editor editor = getSharedPreferences("SwitchButton", MODE_PRIVATE).edit();
editor.putBoolean("onKrsClick", false);
editor.commit();
ParsePush.unsubscribeInBackground("egersund");
}
}
public void onEgsClick (View view) {
boolean on = ((Switch) view).isChecked();
if (on) {
SharedPreferences.Editor editor = getSharedPreferences("SwitchButton", MODE_PRIVATE).edit();
editor.putBoolean("onEgsClick", true);
editor.commit();
ParsePush.subscribeInBackground("egersund");
} else {
SharedPreferences.Editor editor = getSharedPreferences("SwitchButton", MODE_PRIVATE).edit();
editor.putBoolean("onEgsClick", false);
editor.commit();
ParsePush.unsubscribeInBackground("egersund");
}
}
Override the onCreate method of that activity class and attempt to load the values you saved in SharedPreferences.
krspush.setChecked(sharedPrefs.getBoolean("onKrsClick",false));
findviewbyid will crash unless called after the view is created ie, in the oncreate method.
Consider using click listener on your switches.
I don't see the point of this line of code "SharedPreferences sharedPrefs = getSharedPreferences("SwitchButton", MODE_PRIVATE)"
Here is how you use shared preferences : https://stackoverflow.com/a/23024962/2590252
You better look into some samples to learn about best coding practices http://developer.android.com/samples/index.html

How to write encrypted app data and decrypte it

I want to store my app data in a file so it could be accessed every time from the app - for example: money, user score, user current sprite...
I have never seen encryption in my life, and I wanted to know if there is an easy way to encrypt data and write it to the phone, and then decrypt it next time the app is open.
If there is no easy way, it would be great if someone could explain how the encryption/decryption works to me.
Use SharedPreferences.
I've used them, and you dont need to encrypt the data.
http://developer.android.com/guide/topics/data/data-storage.html#pref
EXAMPLE(from developer.android):
public class Calc extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
}
#Override
protected void onStop(){
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
// Commit the edits!
editor.commit();
}
}

Run a piece of code only once when an application is installed [duplicate]

This question already has answers here:
Run code only once after an application is installed on Android device
(5 answers)
Closed 7 years ago.
I want to run a piece of code only once in my application and is when i run it for the first time (newly installed app). How could i do this, can anyone explain giving a piece of code.
Actually, in my android project i want to create database and insert some values on the first run only. After that, that particular piece of code should not run again. How can i achieve this mechanism through SharedPreferences or Preferences.
Sample code will be more helpful.
Before all you can use SQLiteOpenHelper. It is preferred way to do things with database. This class have a onCreate(SQLiteDatabase) method, that called when first creating database. I think it suits you well.
If you want more flexibility and your first time logic is not tied only with database, you can use sample provided earlier. You just need to put it in startup spot.
There are 2 startup spots. If you have only single activity, you can put your code in onCreate method, so it will be like this:
public void onCreate(Bundle savedInstanceState) {
// don't forget to call super method.
super.onCreate(savedInstanceState);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (!prefs.getBoolean("firstTime", false)) {
// <---- run your one time code here
databaseSetup();
// mark first time has ran.
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("firstTime", true);
editor.commit();
}
}
Don't forget to put activity declaration in manifest, as well as it's intentfilters (action = MAIN, category = LAUNCHER).
If you have more than one activity and you don't want to duplicate your startup logic you can just put your initialization logic in Application instance, that is created before all activities (and other components, such as services, broadcast recievers, content providers).
Just create class like that:
public class App extends Application {
#Override
public void onCreate() {
super.onCreate();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (!prefs.getBoolean("firstTime", false)) {
// <---- run your one time code here
databaseSetup();
// mark first time has ran.
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("firstTime", true);
editor.commit();
}
}
All you need for this to work, is put in application tag in AndroidManifest.xml attribute android:name=".App".
<!-- other xml stuff -->
<application ... android:name=".App">
<!-- yet another stuff like nextline -->
<activity ... />
</application>
You could try :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences wmbPreference = PreferenceManager.getDefaultSharedPreferences(this);
boolean isFirstRun = wmbPreference.getBoolean("FIRSTRUN", true);
SharedPreferences.Editor editor = wmbPreference.edit();
if (isFirstRun){
// Code to run once
editor.putBoolean("FIRSTRUN", false);
editor.apply();
}
Write this in your first activity on create. Then after the code will not execute again.
here's what I do in those situations :
wmbPreference = PreferenceManager.getDefaultSharedPreferences(this);
isFirstRun = wmbPreference.getBoolean("FIRSTRUN", true);
if (isFirstRun)
{
// Do your magic here
SharedPreferences.Editor editor = wmbPreference.edit();
editor.putBoolean("FIRSTRUN", false);
editor.commit();
}else{
//what you do everytime goes here
}
hope this helps
Wherever you need to run this code in your app:
Check if boolean firstTime is True in shared preferences
If not
Run the one time code
Save firstTime as true in shared preferences
Something like this:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(!prefs.getBoolean("firstTime", false)) {
// run your one time code here
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("firstTime", true);
editor.commit();
}

How can i save the config of my app without using a database??? (using simple textfile)

i need to save a simple field to configurate my APP, cause this, i wont use a database (it's only a field...), i need to save true or false value for this field on a file, and everytimes a section of my app wanna check if it is true they have to check this textfile, and not to open a connexion to a database
i need to save the config for ever... i mean that when i exit from my app, and for example, i shut down my android device, when i start my device again and start my app, the config have to be saved
is this possible? how can i do it? i can't find any information about that
EDIT: i have problems with the first answer... this code is on my oncreate method:
static SharedPreferences settings;
static SharedPreferences.Editor configEditor;
settings = this.getPreferences(MODE_WORLD_WRITEABLE);
if (settings.getBoolean("showMeCheckBox", true))
showMeCheckBox.setChecked(true);
else
showMeCheckBox.setChecked(false);
applyButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Perform action on clicks
if (showMeCheckBox.isChecked()) {
configEditor.putBoolean("showMeCheckBox", true);
} else {
configEditor.putBoolean("showMeCheckBox", false);
}
}
});
ok, but this doesn't works... allways is selected... always true, like the default value... doesn't matter if i checked or unchecked it.... :S
i suggest not to use a textfile but the Preference Editor.
static SharedPreferences settings;
static SharedPreferences.Editor editor;
settings = this.getPreferences(MODE_WORLD_WRITEABLE);
editor = settings.edit();
//store value
editor.putString("Preference_name_1", "1");
//get value
//eill return "0" if preference not exists, else return stored value
String val = settings.getString("Preference_name_1", "0");
Edit: you have to initialize the configEditor and after setting a value, you have to commit
editor = settings.edit();
editor.putBoolean("name",true);
editor.commit();

Categories

Resources