save button state on android studio - android

I am creating an app with lot of buttons. I programmed the buttons so if I don't click them, the background color stays white and if I click them the background color turns to green. I want to save this green button. so if I close the app and reopen it I want previously turned green buttons to remain green but unfortunately reopening the apps makes the button white. What can I do?

We can solve this with SharedPreferences.
SharedPreferences will store the data that you want.
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
prefs.edit().putBoolean("button1", true).apply();
This above code for to write your data to SharedPreferences
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
boolean isButtonPressed = prefs.getBoolean("button1", false);
Above code for read your button value with key ("button1"). default value would be false beacuse if you not stored any values for that key it will return as false.

I think your best choice would be to just use SharedPreferences. SharedPreferences let you easily save values. For example:
When you press a button
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
prefs.edit().putBoolean("button_1_pressed", true).apply();
When you start your activity. I.e (OnCreate())
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
boolean isButtonPressed = prefs.getBoolean("button_1_pressed", false);
if (isButtonPressed) {
// TODO make button green
}

Related

Saving Fragment's State Through out the application

I have an application where app has both online & offline mode.
Once the fragment is loaded a network call is made and data is set.
The user makes some changes into fragment UI like adding buttons, Editing TextBoxes etc. I have to maintain that state throughout the application.
I have next & previous buttons, when i press on previous button on the fragment is reloading even though i tried to adding it to back stack while replacing it and calling getActivity().onBackPressed();.
Things I have Tried :
1) saving the values into bundles is too much data & hard ti retrieve due to bulk of data/values.
If you use viewpager, you can keep the last state of the fragments and it will not reload untill the offscreen limit u set as below.
mViewPager.setOffscreenPageLimit(limit); //limit: integer value >=1
If you have large number of data you want to save, use SQLite, otherwise you can use Shared Preferences
For more info visit this link
First get the reference to your shared preferences file
Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences("my_preferences", Context.MODE_PRIVATE);
after this write to Shared Preferences with
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("key", "value");
//use editor.apply() if you want to save your data imedialtly
editor.commit();
when you want to retrieve the data (onCreateView/onViewCreated)
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
EditText editex = (EditText) view.findViewById(R.id.your_view_id);
editext.setText(sharedPref.getString("key", defaultValue))
}
But keep in mind, Shared Preferences will save and keep your data even if your app is killed/destoyed

SharedPreferences in Android saving the visibility of an ImageView

I have a menu activity that acts as a level selector. When the user finishes a level (activity) and returns to the menu, I want it to set an image visible in the menu to show that said level has been completed. Also, I want this info to save from a session to another.
My aproach has been to try SharedPreferences. This is the code from the level activity that writes the save:
private int levelNumber
SharedPreferences save = getSharedPreferences("SaveGame", MODE_PRIVATE);
SharedPreferences.Editor editor = save.edit();
editor.putInt("levelComplete",levelNumber);
editor.commit();
GameActivity.this.finish();
This is the relevant code from the menu that reads the save and sets the image visible based on the levelNumber:
clear_stage = new ImageView[clear];
clear_stage[0] = (ImageView)findViewById(R.id.clear1);
clear_stage[1] = (ImageView)findViewById(R.id.clear2);
clear_stage[2] = (ImageView)findViewById(R.id.clear3);
clear_stage[3] = (ImageView)findViewById(R.id.clear4);
clear_stage[4] = (ImageView)findViewById(R.id.clear5);
SharedPreferences save = getApplicationContext().getSharedPreferences("SaveGame", MODE_PRIVATE);
clear = save.getInt("levelComplete", 0);
clear_stage[clear].setVisibility(View.VISIBLE);
I have the visibility set to "gone" in the xml, by the way.
Now, my main problem is that the visible image changes every time that a level is completed, and the last image goes invisible again (gets overwritten).
Is there a way to store the clear value each time a level is complete?
I tried with:
SharedPreferences saveall = getSharedPreferences("SaveGame", MODE_PRIVATE);
SharedPreferences.Editor editor = saveall.edit();
editor.putInt("clear_stage",clear);
editor.commit();
But it isn't working, and I don't really know what I should do next. Ask me anything if the post wasn't clear enough.
I think your problem is that your'e loading as an int, not an array. I would look here for a better explanation. Is it possible to add an array or object to SharedPreferences on Android particularyly sherifs' answer

checkbox value in other activity

hy, everyone
i'm searching for a few days a solution for one problem i tried to search but i didn' find an answer for my problem so i decided to ask you maybe someone it will so kind and wil explaine to me ho can solve my problem.
So i have two activities, a configure one and a main one, my problem is that when i check one checkbox in the configure activity (i succeed to save the checkbox state so when i check it will be checked even if i leave the configure activity), but i don't know how can i use the checkbx state in the main activity. i found many suggestions but for for me nothing worked.
thank you in advance.
thank you for all for the answers but i not succeeded in this way to solve my problem, and with your suggestions i did the following: in the second activity(where i have the CheckBox): i have one Save function where i save with SharedPreferences the Checkbox State( even if i close the activity or anything else the state of Checkbox it's keeping his state) and i have made a Load function where when i load back the activity it's loading the previous state so inside this activity i thing it is ok, But in this case how can use the load function's value (in fact the checkbox value) int the MainActivity.
I'm sorry for inconvenience but i'm knew but i would like to learn.
Thank you ones again.
Store the value in SharedPreference to get the value of checkbox
chkIos.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
SharedPreferences sharedPreferences = context.getSharedPreferences("settings", Context.MODE_PRIVATE);
Editor editor = sharedPreferences.edit();
editor.putString("checkboxState",((CheckBox) v).isChecked());
editor.commit();
//Save the state of checkbox in sharedPreference
}
}
});
In main activity get the state like this.
SharedPreferences sharedPreferences = context.getSharedPreferences("settings", Context.MODE_PRIVATE);
String stateValue = sharedPreferences.getString("checkboxState);
i guess the sharepreferences will resolve that
SharedPreferences.Editor editor = app_preferences.edit();
editor.putBoolean("Checkbox", value);
editor.commit();
SharedPreferences app_preferences =
PreferenceManager.getDefaultSharedPreferences(this);
boolean value = app_preferences.getBoolean("Checkbox", false);
You can use SharedPreferences to save the state of your CheckBox in the device so you can retrieve it from another Activity.
Here is an example how to use them. Also you can check this YouTube video that shows you how to make preferences screen for your Activities.

Error loading SharedPreferences on startup

I'm obviously doing something wrong. On my splash screen, when it decides which activity to go to, I have the following code:
SharedPreferences getPrefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
boolean disclamerChecked = getPrefs.getBoolean("disclamer", false);
boolean medicalScreeningChecked = getPrefs.getBoolean("screening", false);
So, I'm trying to read 2 Boolean that should be false on app installation and
when the setup is done it should be permanently true.
Now, in my Activities (Disclamer only at the moment) I have the following thing:
private void setDisclamerPropertie() {
// TODO Auto-generated method stub
startupPrefs= getSharedPreferences("startupPrefs", MODE_WORLD_WRITEABLE);
SharedPreferences.Editor editor = startupPrefs.edit();
editor.putBoolean("disclamer", true);
editor.commit();
return;
}
This function is called in On Create function, and when "accept" button is clicked it should save the Shared Preference (Or at least that is what I need to happen).
Button works, it goes to next activity and that one goes to next again, but when I reload the App, it seems that Boolean are not saved and app asks again for the confirmations.
So, where am I wrong, in writing preferences, or something is missing in reading correct preferences?
You are reading from the default shared preferences, but writing to a named one ("startupPrefs"), so there are 2 separate instances of shared preferences
You're using different preferences.
startupPrefs= getSharedPreferences("startupPrefs", MODE_WORLD_WRITEABLE);
This should also be:
startupPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

Updating Checkbox value in Preference Screen upon changing the value in SharedPreferences in Android

I have an app which uses the user's location. I have a dialog(pic below) asking user's permission to "Allow" or "Disallow" the app to use the user's location ( dialog pops up the first time users opens the app after installation OR when user tries to use the location based service while using user location is "Disallow"-ed by the user).
I also use preference item(a checkbox)(pic below) in PreferenceActivity where the user can the toggle his preference.
To change the value of the sharedpreference I have use this code
public void onClick(DialogInterface dialog, int id)
{
sharedPrefs =getSharedPreferences("prefs",MODE_WORLD_WRITEABLE);
Editor editor = sharedPrefs.edit();
editor.putBoolean("locationPermission", true);
editor.commit();
}
I had expected the checkbox value to change automatically depending on the dialog selection as the key "locationPermission" holds the value to the checkbox. But it is not so.
Now how do I map the dialog(pic 1) selection to the checkbox value(pic 2)?
The issue was solved by using
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
instead of
sharedPrefs = getSharedPreferences("prefs", MODE_WORLD_WRITEABLE);
You can call addPreferencesFromResource in the onCreate of your PreferenceActivity so that your UI is populated from the preferences.
Also, you may want to make sure that your CheckBoxPreference has android:persistent-"true" in its XML definition.

Categories

Resources