Android SharedPreferences issue - java

I need a little help with Android Shared Preferences. I'm trying to put a boolean type in SP and make it visible from every other activity in my application.And I want to be able to change the state of boolean type to true/false from another activity so I can make some changes in the UI depending on that boolean value.
For now I'm using this piece of code,which I understand but it's not correct.
Here it is :
Activity 1:
boolean isLoggedIn = false;
SharedPreferences isLogged = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = isLogged.edit();
editor.putBoolean("isLoggedIn", isLoggedIn);
editor.commit();
Activity 2 :
boolean isLogged=true;
int mode = Activity.MODE_PRIVATE;
SharedPreferences mySharedPreferences;
mySharedPreferences=getSharedPreferences("isLoggedIn",mode);
mySharedPreferences.edit().putBoolean("isLoggedIn", isLogged);
boolean bool = mySharedPreferences.getBoolean("isLoggedIn",false);
Log.w("Boolean","Boolean state : "+bool);

In Activity 2 try using like this and it will work
mySharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
and remove below line
mySharedPreferences.edit().putBoolean("isLoggedIn", isLogged);

Put edit.commit(); after mySharedPreferences.edit().putBoolean("isLoggedIn", isLogged);
This will help you to get correct value.

Related

Quit showing an Activity when CheckBox is checked

I have got a DialogActivity with a "do not show anymore" CheckBox.
What I need it to do is exactly like the CheckBox says. When the CheckBox is checked the Activity doesn't have to be displayed to the user anymore, no matter if the app is restarted or killed.
public class PopUpInfoActivity extends Activity {
static final String PREFS = "preference_file";
#Override
public void onCreate(Bundle state) {
setContentView(R.layout.popupinfo_layout);
CheckBox chk = (CheckBox) findViewById(R.id.dontshow_checkbox);
chk.setChecked(PreferenceManager.getDefaultSharedPreferences(this).getBoolean("value", false));
chk.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//store isChecked to Preferences
SharedPreferences settings = getSharedPreferences(PREFS, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("isChecked", false);
PreferenceManager.getDefaultSharedPreferences(PopUpInfoActivity.this).edit().putBoolean("value", isChecked).apply();
}
});
Intent intent = new Intent(PopUpInfoActivity.this, ChordsListActivity.class);
if (!chk.isChecked()) {
// run activity
super.onCreate(state);
} else {
startActivity(intent);
}
}
}
If I do it like this the App crashes.
If I replace the else with:
else {
onStop()
}
The code doesn't work as expected.
I would really appreciate if you could help me fix this problem!
EDIT:
This is what I have got in my ChordsListActivity, which is the activity that calls the PopUpInfoActivity but I do not get what I should put in my if() statement.
Intent legendaIntent = new Intent(ChordsListActivity.this, PopUpInfoActivity.class);
if(/*what's here?*/)
startActivity(legendaIntent);
In that MainActivity read your preference key (Show_Dialog), if it is true then launch PopUpInfoActivity otherwise launch ChordsListActivity.
The logic should be in the Mother Activity
In your PopUpInfoActivity you should only edit the preference key to false if the user checks out the ChekBox
To do so, please create a preferences.xml file under res/xml, inside this file you have to create a key (Boolean) that you will store inside the status of PopUpInfoActivity.Checkbox, the default will be (True).
here is an example
<CheckBoxPreference
android:key="Show_Dialog"
android:defaultValue="true" />
From your MainActivity you should read this value like this:
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
Boolean showDlg = sharedPref.getBoolean("Show_Dialog", true);
if the showDlg is true then you popup your dialog, otherwise continue what you want to do.
of course you need to change the value of Show_Dialog if the user checks the checkbox, you can do it like this:
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor preferencesEditor = sharedPref.edit();
preferencesEditor.putBoolean("Show_Dialog", false);
preferencesEditor.commit();
in this way, you can be sure that your main activity will read the Show_Dialog as false next time the user launches your application
Good luck
Firstly, super.onCreate() must be the first call in any Activity's onCreate().
Secondly, store the value of the SharedPrefence in a boolean instead of directly setting the CheckBox, and use that before setContentView() to finish your current Activity and launch the next one if true. If not, carry on with the UI stuff and anything else you need.

Load SharePrefs Value into textview

So i made a game with a simple score keeping system, It seems that the highscore gets put into the shared prefs correctly, but when trying to load the high score into the activity oncreate the application crashes. this is my code.
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
int score = sharedPref.getInt("SCORE", 0);
String score2 = Integer.toString(score);
text10.setText(score2);
Not sure what i'm doing wrong so any advice will be great!
Here is my save score code
private void savePref(String key, int value) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor edit = sp.edit();
edit.putInt(key, value);
edit.apply();
}
From the log you have shared, it is clear that you have not get the TextView properly. Assuming that you have set the layout, do something like this:
text10 = (TextView) findViewById(R.id.your_textview_id);
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
int score = sharedPref.getInt("SCORE", 0);
String score2 = Integer.toString(score);
text10.setText(score2);
Save SharedPreferences properly, using both name and mode
SharedPreferences sharedPreferences = context.getSharedPreferences("DATA",Context.MODE_PRIVATE);
I think this is happening beacuse, the method that you're using getPreferences(PREFERENCE_MODE_PRIVATE)
returns the preferences saved by Activity's class name as described here :
Retrieve a SharedPreferences object for accessing preferences that are private to this activity. This simply calls the underlying getSharedPreferences(String, int) method by passing in this activity's class name as the preferences name.
So, when you're saving the prefs in SomeActivity it's being saved under the name "SomeActivity"
but when you're getting the prefs in this activity it's returning you the prefs saved under this activity's class name.
So, you should use getSharedPreferences (String name, int mode) method with the same name instead.
source
UPDATE
After looking at the stacktrace looks like your TextView object text10 is null, initialize it and the problem will be solved.

SharedPreferences not saving properly - android

I'm trying to use sharedpreferences to store an integer. Something is wrong though, so the integer won't get saved. Whenever I stop my app the integer won't show up, it isn't there and isn't getting saved. Here's my code that's located in my onCreate() method:
private int point;
//...
SharedPreferences sp = getSharedPreferences("prefs_file",MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("your_int_key", point);
editor.apply();
SharedPreferences sp1 = getSharedPreferences("prefs_file",MODE_PRIVATE);
int highScoreSaved = sp1.getInt("your_int_key", 0);
Try sp1.commit().
Have a look at the developer guide:
https://developer.android.com/guide/topics/data/data-storage.html#pref

SharedPreferences not updating value when returning to Activity, but only keeps initial Activity load value

So I am trying to use SharedPreferences to pass a value from the Activity to a Class. The problem is the following:
On initial loading of the Activity, the value is stored in SharedPreferences but if I exit the Activity and return back, and try to update the value, the SharedPreferences does not seem to update and stays at the value of the initial load of the Activity.
Some class function
private void populatePlayerQueue(){
int category_index;
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this.getContext());
category_index = sharedPreferences.getInt("selected_category", 0);
}
Activity onResume
#Override
public void onResume() {
super.onResume();
int tmp = Integer.parseInt(getIntent().getStringExtra("CategoryIndex"));
//store the category in the shared preferences
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("selected_category", tmp);
editor.commit();
}
What I am trying to do:
I have to send an integer from the activity to a specific class and if I come back to the activity then I need to store the update value and so the class will be able to access the newly updated value again. I only have access to the context and not the activity. This causes errors if I try to create an interface callback to communicate with the activity. So this option is eliminated, hence I am trying anything I can to do that.
For some better result remove the SharedPreference through its key at the time of exit application.
In your case when you exit your application just clear the SharedPreference like:
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove("selected_category"); //Just remove it by its specific key
editor.commit();
Then it will clearly load and save the new value again when you go back to your application on the same key or you can use new one.

SharedPreferences not Reading

I am getting weird problem with my app.
I have set-up one SharedPreference, like this
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
flag = prefs.getBoolean("handle_calls", false);
if (flag) {
SharedPreferences.Editor editor = prefs.edit();
editor.clear();
editor.putBoolean("checkFlag", true);
editor.commit();
}
it was working fine some days before, but now this code is working fine but when I try to read these preferences in my SmsReceiver Class SharedPreferences doesnt read these values and default values are read (false)...Sometimes it work and most of the time it doesnt work at all!
Here is how I am reading the SharedPreferences
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SmsManager sms = SmsManager.getDefault();
//flag = prefs.getBoolean("handle_calls", false);
checkFlag = prefs.getBoolean("checkFlag", false);
checkDecisionFlag = prefs.getBoolean("checkDecisionFlag", false);
This checkDecisionFlag is working fine but checkFlag is taking default values.
Really pissed! Please Help!
remove the editor.clear(); from if condition. as clear will clear all the data from SharedPreference.
if (flag) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("checkFlag", true);
editor.commit();
}
Solved it!
This code was fine, instead the problem was with the life-cycle oriented. I had one another SharedPreference on which this depend. That was getting false again and again.
I think you wanted to use if (!flag) (not flag) on the third line of the first code sample.

Categories