If shared preferences does not contain - java

SharedPreferences mPrefs = getSharedPreferences("IDvalue",0);
if(mPrefs.contains("DATE")) {
//do something
}else {
mPrefs.edit().putString("DATE", currentdate);
mPrefs.edit().commit();
Toast.makeText(this, "changed", Toast.LENGTH_SHORT).show();
}
What i want the code to do is run the first time and show the toast but the second time it is run not show it and run the code inside the first parameters. But as it is now the code just runs the second "else" statement twice and doesn't even run the first. it's as if the string isn't even being put in "DATE"? Is there anything wrong with my code?

Make Editor Object and use it for edit/commit.
You can use below code. it will work fine.
SharedPreferences mPrefs = getSharedPreferences("IDvalue",0);
SharedPreferences.Editor mEditor = mPrefs.edit();
if(mPrefs.contains("DATE")) {
//do something
}else {
mEditor.putString("DATE", currentdate);
mEditor.commit();
Toast.makeText(this, "changed", Toast.LENGTH_SHORT).show();
}

Related

Get the state of a Switch in onCreate()

So my question is how I can get the state of a Switch.
I have this Code:
notificationSwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(notificationSwitch.isChecked()){
System.out.println("Checked");
SharedPreferences.Editor editor = getSharedPreferences("save", MODE_PRIVATE).edit();
editor.putBoolean("value", true);
editor.apply();
notificationSwitch.setChecked(true);
}else{
System.out.println("not checked");
SharedPreferences.Editor editor = getSharedPreferences("save", MODE_PRIVATE).edit();
editor.putBoolean("value", false);
editor.apply();
notificationSwitch.setChecked(false);
}
}
});
The state of the switch is saved in the Shared Preferences and if I start the app the Switch is on the same state as when I left the app. But when I start the app is should print checked or not checked but it doesn't print out anything
I will answer based on the title:
To get the state of the switch in onCreate():
//in onCreate:
SharedPreferences prefrences = getSharedPreferences("save", MODE_PRIVATE);
//false mean if not found set to false as default
boolean stateSwitch = prefrences.getBoolean("value",false);
//set state for switch
notificationSwitch.setChecked(stateSwitch);
//log the state
if(stateSwitch == true){
Log.d("TAG","checked");
}else{
Log.d("TAG","not checked");
}
UPDATE
keep your onclicklistener the same, and add the code I provided before your onclicklistener in onCreate:
1) when you turn switch on and leave activity and come back it must stay on.
2) when you turn switch off and leave activity and come back it must stay off.
3) if you do nothing leave activity and come back it must stay off.

How to check if function is running for the first time?

So I am currently modifying a code.
In the piece of code I am attaching below, mShakeImage.start() is executed every time the activity is first launched.
I want to eliminate this and stop mShakeImage.start() from triggering the first time the activity is launched. How do I achieve this?
CODE
#Override
public void displayEvent(#AccelerationEvent int event, int data) {
if(mCurrentDetectEvent == FeatureAcceleratonEvent.DetectableEvent.FREE_FALL)
{
mShakeImage.start();
Context context = getContext();
//-----------test for position of shake image---------------------
new AlertDialog.Builder(context)
.setTitle("Alert")
.setMessage("This is an alert")
.show();
//---------------call function from CallScreen()------------------
Intent intent = new Intent(context.getApplicationContext(), CallScreen.class);
context.startActivity(intent);
}
Try this code
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
if(sharedPreferences.getBoolean("firstTime", true)){
mShakeImage.start();
sharedPreferences.edit().putBoolean("firstTime", false).apply();
}
First of all you need to put a check on this function, like whether it is executed before are not and for that you need to save a value in sharedpreferences.
Suppose we save a value in sharedpreferences inside that method and check it before the call to that method like
if(!sharedPreferences.getBoolean("firstTime", false))
mShakeImage.start();
now if we check it for first time you install app in device. this condition will be false and your function will be executed.
Now inside mShakeImage function we save/change true value inside sharedPreferences so on second time the condition will not met and mShakeImage will not be called.

Shared Preferences won't save the data

I'm new to Android, and a bit to Java (Don't ask)
I want to use the Shared Preferences, and till to this day everything worked fine, but in my new project the shared preferences won't save the data.
In my onCreate Method I have following code:
preferences = this.getSharedPreferences(KEY, MODE_PRIVATE);
editor = preferences.edit();
preferences.getFloat(TESTEPFLOAT, 0);
preferences.getFloat(TESTCURRENTEPFLOAT, 0);
preferences.getInt(TESTLEVEL, 1);
in my onDestroy Method:
#Override
public void onDestroy(){
super.onDestroy();
editor.putInt(TESTLEVEL, level);
editor.putFloat(TESTEPFLOAT, ep);
editor.putFloat(TESTCURRENTEPFLOAT, currentEP);
editor.apply();
}
I don't know where the problem is, and I hope someone can help me
Don't use onDestroy(). There's no guarantee it will get called. If you put a break point in that method, my guess is it's not getting called when you think it is.
change to this:
preferences = this.getSharedPreferences(KEY, MODE_PRIVATE);
preferences.getFloat(TESTEPFLOAT, 0);
preferences.getFloat(TESTCURRENTEPFLOAT, 0);
preferences.getInt(TESTLEVEL, 1);
to save your data:
#Override
protected void onPause() {
super.onPause();
preferences = this.getSharedPreferences(KEY, MODE_PRIVATE);
editor = preferences.edit();
editor.putInt(TESTLEVEL, level);
editor.putFloat(TESTEPFLOAT, ep);
editor.putFloat(TESTCURRENTEPFLOAT, currentEP);
editor.apply();
}
or use editor.commit(); to save data immediately
Just as #Gavin Wright said, onDestroy don't get called everytime. Move the code to onPause(). onPause() is guaranteed to get called everytime you navigate away from your activity.
#Override
public void onPause(){
super.onPause();
editor.putInt(TESTLEVEL, level);
editor.putFloat(TESTEPFLOAT, ep);
editor.putFloat(TESTCURRENTEPFLOAT, currentEP);
editor.apply();
}

Using Shared preferences to save a string on a button click

So currently I have:
public void SaveText(View view) {
String saved = text.getText().toString();
// TODO
Toast.makeText(getApplicationContext(), R.string.addedfavs, Toast.LENGTH_SHORT).show();
}
How do you save the 'Text' string and save it into shared preferences, without overwriting previous saved strings.
(Note: I've tried using arrays and array lists but I just end up with one result and overwriting it rather than adding to the previously saved strings)
I'm pretty new to this so please don't skip any steps regardless of how insignificant they may seem.
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
while saving
public void SaveText(View view) {
String saved = text.getText().toString();
SharedPreferences.Editor editor=prefs.edit();
editor.put("value",saved);
editor.commit();
Toast.makeText(getApplicationContext(), R.string.addedfavs, Toast.LENGTH_SHORT).show();
}
while retriving
String value=prefs.getString("value");
Read the content which is already stored in your SharedPreferences, append the new value and finally write back to SharedPreferences.

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