this is my settings activity which has got one switch:
settings_inputs_switch = (Switch) findViewById(R.id.settings_inputs_switch);
settings_prefs = getSharedPreferences("settings_prefs", MODE_PRIVATE);
settings_inputs_switch.setChecked(settings_prefs.getBoolean("switch1_state",true ));
settings_inputs_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (settings_inputs_switch.isChecked()){
settings_prefs = getSharedPreferences("settings_prefs", MODE_PRIVATE);
SharedPreferences.Editor editor = settings_prefs.edit();
editor.putBoolean("switch1_state", true);
editor.commit();
}
else {
settings_prefs = getSharedPreferences("settings_prefs", MODE_PRIVATE);
SharedPreferences.Editor editor = settings_prefs.edit();
editor.putBoolean("switch1_state", false);
editor.commit();
}
}
});
how can i get this shared preference value in main activity to do some job based on the value??
One way to achieve this is in your MainActivity read the value of the preference in onResume(). This should get you the latest value each time you get to MainActivity from anywhere.
To read the value, you do it similarly as you write them. In your MainActivity:
#Override
protected void onResume() {
SharedPreferences prefs = getSharedPreferences("settings_prefs", Context.MODE_PRIVATE);
boolean switchState1 = prefs.getBoolean("switch1_state", false);
// Do more stuff
}
(fact: "settings_prefs" is an xml file within your app's local storage)
as stated above one trick i use is to check for changes in onResume() method
You can read preference valve like this in any activity.
SharedPreferences sharedPreference = getSharedPreferences("settings_prefs", Context.MODE_PRIVATE);
boolean value = sharedPreference.getBoolean("switch1_state",false);
SharedPreferences getSharedPreferences (String name, int mode)
Retrieve and hold the contents of the preferences file 'name', returning a SharedPreferences through which you can retrieve and modify its values. Only one instance of the SharedPreferences object is returned to any callers for the same name, meaning they will see each other's edits as soon as they are made.
SharedPreferences sharedPreference = getSharedPreferences("settings_prefs",Context.MODE_PRIVATE);
boolean switchState= sharedPreference.getBoolean("switch1_state",false);
Related
Intent intent1 = new Intent(Questions.this, Questions.class);
startActivity(intent1);
Little problem in my learning.
Sorry for my frenchglish ^^
A variable changes every time, i press a button, it backs up and assigns it ++.
In the button input if the variable == in table REPONSE.Length, It restarts the activity and it REMOVE the backup.
My problem is that the backup does not remove itself while the activity restarts well.
Every time i support the activity it raises again without being able to start again at stage 0.
int REPONSE[]= new int[5]; //tableau des reponses
int Question = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.questions);
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
Question = sharedPreferences.getInt("num", 0);
cardView1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Restart si Question == REPONSE.length
if (Question == REPONSE.length){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove("num");
editor.apply();
Intent intent1 = new Intent(Questions.this, Questions.class);
startActivity(intent1);
}
//Sauvegarde de la variable
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("num", Question++);
editor.apply();
//Incrementation +1
Question++;
}
}); }
Thanks in advance:)
According to the documentation remove() removes a value once commit() is called. So you have to change editor.apply() to editor.commit()
//Restart si Question == REPONSE.length
if (Question == REPONSE.length){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove("num");
editor.commit(); //editor.apply() won't work
There are 3 points that I wold recommend you:
Point 1:
Try giving your Shared preference a name. Example:
sharedPreferences = getSharedPreferences("sharedPrefName", MODE_PRIVATE);
If you are not giving a name to the shared preference android can fall into ambiguity and create a new Sharedpreference thus not affecting the old one.
Even you are creating a new SharedPreference inside the onClick method(this process is wrong), and there the android system is not being able to understand which Shared Preference to use thus not affecting the sharedpreference data that you want to change.
Point 2:
This not so important as the first one but to change the data of an already existing preference you need not to delete the preference instead just change the value, and it will be updated to your requirement:
sharedPreferences.edit().putInt("num", Question++).apply();
Point 3:
Create SharedPreference object once inside the class where it can
have global scope.
Initialize the SharedPreference only once in an activity inside
onCreate method.
Make your code something like this:
public class MainActivity extends AppCompatActivity {
SharedPreferences sharedPreferences;
ConstraintLayout layout;
int Question = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_main);
layout = findViewById(R.id.layout);
sharedPreferences = getSharedPreferences("sharedPrefName", MODE_PRIVATE);
Question = sharedPreferences.getInt("num",0);
layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sharedPreferences.edit().putInt("num", Question++).apply();
}
});
}
}
I am trying to make an android app that allows users to block apps for a specific period of time. So I have a listview of installed apps in a fragment with a switch button next to it.
I want it to stay checked when the user checks its or unchecks it after they press back and exit the app.
I am trying to achieve this using setOnCheckedChangeListener and Shared Preferences; however; I am having trouble saving the button state in my BaseAdapter class.
holder.ck1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (holder.ck1.isChecked()) {
//itemChecked[position] = true;
b = true;
holder.ck1.setChecked(b);
Log.i("This is", " checked: " + position);
SharedPreferences.Editor editor = context.getSharedPreferences("com.ibc.android.demo.appslist.app", Context.MODE_PRIVATE).edit();
editor.putBoolean("checkBox1", b);
editor.commit();
} else {
//itemChecked[position] = false;
b= false;
holder.ck1.setChecked(b);
Log.i("This is", " not checked: " + position);
SharedPreferences.Editor editor = context.getSharedPreferences("com.ibc.android.demo.appslist.app", Context.MODE_PRIVATE).edit();
editor.putBoolean("checkBox1", b);
editor.commit();
}
}
});
sharedPrefs = context.getSharedPreferences("PACKAGE_NAME", Context.MODE_PRIVATE);
holder.ck1.setChecked(sharedPrefs.getBoolean("checkBox1",false));
// I think that maybe instead of false I should put the boolean b I defined in the method but I am not sure how to get it .
return convertView;
}
How I do I modify this to reach to desired result?
I think whenever the activity created it automatically calls onCheckedChange and your SharedPreferences overwrite by default values. so I think you can use onStop to update the SharedPreferences.
holder.ck1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b)
{
SharedPreferences.Editor editor = context.getSharedPreferences("PACKAGE_NAME", Context.MODE_PRIVATE).edit();
editor.putBoolean(pakagename, b);
editor.commit();
}
});
sharedPrefs = context.getSharedPreferences("PACKAGE_NAME", Context.MODE_PRIVATE);
holder.ck1.setChecked(sharedPrefs.getBoolean(pakagename,false));
return convertView;
}
pakagename holds the package name of that particular listitem. Otherwise if you are targeting above api level 11, you can use a set in sharedpreferences to store all the checked package names. This is the easy way. Otherwise you can save the list of checked applications in a database.
I have achieved the requested feature. Check my code:
final SharedPreferences sharedPreferences = getSharedPreferences("conditionCheck", MODE_PRIVATE);
switchCompat.setChecked(sharedPreferences.getBoolean("switchCondition",false));
switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
final SharedPreferences sharedPreferences = getSharedPreferences("conditionCheck", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
if (switchCompat.isChecked()) {
Toast.makeText(getApplicationContext(), "Checked Condition True", Toast.LENGTH_LONG).show();
editor.putBoolean("switchCondition",switchCompat.isChecked());
editor.commit();
} else {
Toast.makeText(getApplicationContext(), "Checked Condition False", Toast.LENGTH_LONG).show();
editor.putBoolean("switchCondition",switchCompat.isChecked());
editor.commit();
}
}
});
In my app I am storing integer and string data from different Fragments.
This data is succesfully retrieved in the same Fragment.
The String data is succesfully retrieved over the whole application.
The Integer data however cannot be retrieved from different activities. In the same Fragment however it can be. If i try to get an integer from a different activity, it´s always giving me my set default value.
Here is my code. Note that i´m already using constants to retrieve data.
to save numbers:
public void saveNumberChange(String s, int data){
String help = "com.example.test2.PREFERENCE_FILE_KEY_"+username;
Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(help, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(s, data);
editor.commit();
}
and get them back out:
public int getNumber(String s){
int data;
String help = "com.example.test2.PREFERENCE_FILE_KEY_"+username;
Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(help, Context.MODE_PRIVATE);
data = sharedPref.getInt(s, 0);
return data;
}
The funny thing is, when i´m storing the integer as strings, they can again be retrieved in the same activity, not though from another activity. With pure strings everything is fine.
Some more code:
Save integer:
saveNumberChange(BeyouApplicationClass.AGE, valueage);
Get integer:
getNumber(BeyouApplicationClass.AGE);
Thanks for your help. I hope you can help me.
You cant access it from another activity because you are only saving it on that activity using the context of that activity.
solution:
instead of using the context.getSharedPreferences of the activity use the PreferenceManager.getDefaultSharedPreferences for your whole application to share data among its activity
example:
saveNumberChange
public void saveNumberChange(String s, int data){
Context context = getActivity();
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(s, data);
editor.commit();
}
getNumber
public int getNumber(String s){
int data;
Context context = getActivity();
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
data = sharedPref.getInt(s, 0);
return data;
}
Try getting your preferences this way:
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
in all activities, and getting the editor the same way
So what i found out is following.
For everybody that has the same problem:
Saving shared preferences from inside a fragment will lead to the problem i described earlier.
Only that specific fragment will be able to get the information back out.
So always save from fragment by calling its host activity.
What i did is this:
public static void saveNumberChange(String s, int data){
String help = "com.example.test2.PREFERENCE_FILE_KEY_"+username;
SharedPreferences sharedPref = context.getSharedPreferences(help, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(s, data);
editor.commit();
}
public static int getNumber(String s){
int data;
String help = "com.example.test2.PREFERENCE_FILE_KEY_"+username;
SharedPreferences sharedPref = context.getSharedPreferences(help, Context.MODE_PRIVATE);
data = sharedPref.getInt(s, 0);
return data;
}
make your method static so it can be called from within the attached fragment and everything works fine.
Sometimes after restarting the app resets the sharedpreferences on devices with API level > 13.
The sharedpreferences are set at the beginning of the app (first activity of the app).
code:
Public void saveCountry(Context context, String countryCode) {
SharedPreferences settingsActivity = context.getSharedPreferences("preferences", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settingsActivity.edit();
editor.putString("key_country", countryCode);
editor.commit();
setDefaultChannels(context);
}
public String getCountry(Context mContext) {
SharedPreferences settingsActivity = mContext.getSharedPreferences("preferences", Context.MODE_PRIVATE);
String country = settingsActivity.getString("key_country", null);
return country;
}
I dont know what im doing wrong and why it is happening. I noticed this specially after receiving a push-notification to a detailactivity.
Are you calling the saving methods at the beginning of your app like this?
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
saveCountry();
Because if you are, you are calling it every time at startup, so the country will be overridden with whatever data countryCode equals at startup, which could be nothing. So maybe you should have some code that only calls that on first run.
Here is how I have it implemented in my app.
boolean firstRun;
final SharedPreferences firstRunPref = getSharedPreferences(PREFS_NAME, 0);
firstRun = firstRunPref.getBoolean("firstRun", true);
if(firstRun==true){
saveCountry();
SharedPreferences.Editor editor3 = firstRunPref.edit();
editor3.putBoolean("firstRun", false);
editor3.commit();
}
I want to save a flag for recognizing that my app is run for the first time or not. For this simple job I don't want to create database..
Is there a simple option to do this? I want to save and read little pieces of information only.
Use sharedPreference or files to save the data but better option is sharedPreference.
For Retrieving
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
For Saving
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", true);
editor.commit();
Use SharedPreferences.
SharedPreferences preferences = getSharedPreferences("prefName", MODE_PRIVATE);
SharedPreferences.Editor edit= preferences.edit();
edit.putBoolean("isFirstRun", false);
edit.commit();
A proper way to do this is by using the Android class SharedPreferences which is used for things like this.
Storing Settings
SharedPreferences settings = getSharedPreferences(NAME_OF_PREFERENCES, MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("appPreviouslyStarted", true);
editor.apply();
Don't forget to apply or your mutations to the settings won't be saved!
You can create multiple settings by using different NAME_OF_PREFERENCES. The settings are stored on the device so will be available after closing the application.
When you try to retrieve NAME_OF_PREFERENCES that is not already created, you create a new one. See more behavior like this here.
apply() versus commit()
You can use editor.apply() as well as editor.commit(), the only difference is that apply() does not return a boolean value with if the edit was successful or not. editor.apply() is therefor faster and more commonly used.
What is MODE_PRIVATE
You can see all about the different modes here. For your case MODE_PRIVATE is fine.
Retrieving settings
SharedPreferences settings = getSharedPreferences(NAME_OF_PREFERENCES, MODE_PRIVATE);
boolean silent = settings.getBoolean("silentMode", false);
When retrieving a settings from a SharedPreferences object you always have to specify a default value which will be returned when the setting was not found. In this case that's false.
I suggest you to go for SharedPreference persistent storage. Its very easy and fast storing/retrival for small amount of information.
See the code to get the value from SharedPreference
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
and to Store value in SharedPreference
// 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);
You can do one class for example:
(like a object for instance)
import android.content.Context;
import android.content.SharedPreferences;
public class SettingsMain {
Context context;
SharedPreferences preferences;
SharedPreferences.Editor editor;
private static final String PREFER_NAME = "settingsMain";
public static final String KEY_VIBRATE = "switchVibrate";
public SettingsMain(Context context) {
this.context = context;
setPreferences();
}
private void setPreferences(){
preferences = context.getSharedPreferences(PREFER_NAME, context.MODE_PRIVATE);
editor = preferences.edit();
}
public void cleanPreferences(){
editor.clear();
editor.commit();
}
public void setStatusVibrate(Boolean status){
editor.putBoolean(KEY_VIBRATE, status);
editor.commit();
}
public Boolean getstatusVibrate(){
return preferences.getBoolean(KEY_VIBRATE, true);
}
}
On your activity call:
public class Home extends AppCompatActivity {
private SettingsMain settings;
private SwitchCompat switchVibrate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.master);
setResources();
getSettings();
}
private void setResources(){
switchVibrate = (SwitchCompat) findViewById(R.id.master_main_body_vibrate_switch);
switchVibrate.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
settings.setStatusVibrate(isChecked);
}
});
}
private void getSettings(){
settings = new SettingsMain(this);
switchVibrate.setChecked(settings.getstatusVibrate());
}
}
What about using static variables globally?
You can do this as given in this tutorial. I know handling Content providers are unnecessary just to keep some flags.
Else you can check out Shared Preferences provided by Android. Here's a good example to get started.
This would be my recommendation.