SharedPreferences return same value even after editing - android

I changed shared preferences value but it still returns old one. What am I missing?
This code executed when the user clicks on the item in RecyclerView. So on the first click, I get message " this true" as expected. But on second click I also get " this true", but expect "this false".
SharedPreferences prefs = context.getSharedPreferences(MY_PREF, Context.MODE_PRIVATE);
boolean value = prefs.getBoolean(KEY_PREF, true);
if (value) {
Log.v(LOG_TAG, "this true");
Log.v(LOG_TAG, "editing value..");
SharedPreferences.Editor prefs = context.getSharedPreferences(MY_PREF, MODE_PRIVATE).edit();
prefs.putBoolean(KEY_PREF, new_value);
prefs.apply();
} else {
Log.v(LOG_TAG, "this false");
}

All you store is true, always, so there's no way to show this false as it never gonna happen. In fact, your code will not compile as new_value is never declared not assigned.
PS: there's no sense to call getSharedPreferences() second time. You got it already in prefs prior entering your if() block.

The call prefs.apply is asynchronously. You may not see the immediate change. Instead you could use prefs.commit which is synchronously.

Related

How to know the last button clicked in android using sharedpreference?

I have two buttons, Now how I can know the last button clicked using sharedpreference when start the activity again ?
the code:
private SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
init in onCreate:
sharedPreferences = getSharedPreferences("MyPref", Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
I tried to do this but absolutely wrong way
if (sharedPreferences.getString("lamp", "on")) {
Toast.makeText(this, "onnnn", Toast.LENGTH_SHORT).show();
}
if (sharedPreferences.getString("lamp", "off")){
Toast.makeText(this, "offfff", Toast.LENGTH_SHORT).show();
}
first button
public void lampOff(View view) {
Log.d(tag, "lampOFF");
lamp_notConnected_Image.setVisibility(View.INVISIBLE);
lamp_Connected_Image.setVisibility(View.VISIBLE);
editor.putString("lamp", "off");
editor.commit();
}
seconde button:
public void lampOn(View view) {
Log.d(tag, "lampO");
lamp_notConnected_Image.setVisibility(View.VISIBLE);
lamp_Connected_Image.setVisibility(View.INVISIBLE);
editor.putString("lamp", "on");
editor.commit();
}
The problem lies in your condition if (sharedPreferences.getString("lamp", "on")), you aren't comparing this string to anything, either use
if (sharedPreferences.getString("lamp", "on").equals("on"))
or
save the value as boolean editor.putBoolean("lamp", true);, then you can compare the way you were doing: if (sharedPreferences.getString("lamp", true))
Note that here ("lamp", "on") the fist parameter is the identification, and the second is the default value, in case nothing is stored there yet.
See more in SharedPreferences
You need to check the shared preference value in onCreate method like:
if (sharedPreferences.getString("lamp", "off").equals("on")) { //assumed "off" as default
Toast.makeText(this, "onnnn", Toast.LENGTH_SHORT).show();
// on button is pressed last time
}
else{
Toast.makeText(this, "offfff", Toast.LENGTH_SHORT).show();
// off button is pressed last time or no button press so far
}

Execute a piece of code once

I am currently developing an app that requires the data to be fetched from server and stored in my local data base.To ensure that the piece of code runs only once I am doing the following thing.
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean dialogShown = settings.getBoolean("dialogShown", false);
if (!dialogShown) {
//Asyntask executed here
if (haveNetworkConnection()) {
new xyz().execute();
} else {
Toast.makeText(getApplicationContext(), "Sorry... No Internet Connection", Toast.LENGTH_LONG).show();
}
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("dialogShown", true);
editor.apply();
}
Above I am setting the shared preference so that it gets executed only once.Now the Problem is in case if there is no internet connection the shared preference will be executed and the data will not be loaded how can I overcome this situation.Any help Appreciated
Now the Problem is in case if there is no internet connection the
shared preference will be executed and the data will not be loaded how
can I overcome this situation.
Instead of updating value when dialogShown is false, update value in SharedPreferences when Network connection is available otherwise make it false:
if (haveNetworkConnection()) {
new xyz().execute();
// update value in SharedPreferences for dialogShown to true
} else {
// update value in SharedPreferences for dialogShown to false
}
Or use onPostExecute method of xyz class for updating flag value when all operation is successful
You can check for the network connection first.
if (haveConnection()){
if(!dialogShown){
new xyz().execute
dialogShown = true;
}else
//already done
}
}
The above code should check for a connection first then check for a dialogShown variable being false. The con of this approach is the constant pinging of the connection to check if it exists. Depending on how you are using the enclosing method this might cause a design decision review. You can always use onPostExecution() instead.

Android Wear: How to implement voice action "Stop running"

I want to implement voice actions, "start running" and "stop running".
"Start running" works fine, but "stop running" doesn't work.
My app has one activity with several fragments.
When I speak "stop running", the activity is destroyed and created. My workout data is lost.
setRetainInstance(true) has no effect.
Change launchMode to singleTask/singleTop/singleInstance has no effect.
I saved workout data in onSaveInstanceState(), but it's lost when a new activity is created.
Is there any other way?
I'm not sure if this is too obvious, but have you considered using SharedPreferences?
To save data:
sPref = getPreferences(MODE_PRIVATE);
testNum = 2;
SharedPreferences.Editor editor = sPref.edit();
editor.putInt("testName", testNum);
editor.commit();
To get data:
sPref = getPreferences(MODE_PRIVATE);
int retrievedTestNum = sPref.getInt("testName",-1);
System.out.println("The number you saved was " + retrievedTestNum + "!");
You can also save data in arrays and store it in the SharePreferences.
If this is too simple for you, you can grab a mySQL database, which is much more robust.

Create a function that fires only once after app is installed on phone

I'm developing a mobile app using ApacheCordova/Phonegap.
I need a function that sends a SMS to me once per install. If I put my function on "DeviceReady" it will be run each time the app opens.
Is there any solution for a function to be run when app is installed OR when it runs for first time?
Any suggestion would be appreciated.
Check if it is the first time with a method and then perform the action if that method determines that it is the first time.
Ex:
isFirstTime() Method
private boolean isFirstTime()
{
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
boolean ranBefore = preferences.getBoolean("RanBefore", false);
if (!ranBefore) {
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("RanBefore", true);
editor.commit();
// Send the SMS
}
return ranBefore;
}
You may want to add it to your onCreate()
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
topLevelLayout = findViewById(R.id.top_layout);
if (isFirstTime()) {
topLevelLayout.setVisibility(View.INVISIBLE);
}
I added a field to the localstorage and on startup just check if that field exists. So something like this:
if (window.localStorage.getItem("installed") == undefined) {
/* run function */
window.localStorage.setItem("installed", true);
}
Edit: The reason I prefer this over the other methods is that this works on iOS, WP, etc as well, and not only on android
This should be what u are searching for:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(!prefs.getBoolean("firstTime", false))
{
// run your one time code
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("firstTime", true);
editor.commit();
}
Use some boolean value if its true don't call that function other wise call that function example is here
if(smssent!=true)
{
//call sms sending method
}
else
{
//just leave blank or else notify user using some toast message
}
Note:-the boolean value store in some database like sharedprefernce or sqllite, files....

Android Service getSharedPreferences Problems

So basically, my service displays a notification which can be turned off if the user wishes.
The setting is controlled from within the application and is set through a PreferenceActivity.
When exiting the activity:
public void onDestroy(){
prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
debug.postLog(Log.DEBUG, "Settings", "("+this.toString()+") showNotification: " + prefs.getBoolean("showNotification", true));
Shows the correct value, if the user unchecks the checkbox, it shows false and vice versa.
Meanwhile, when I call this at any time in my service:
prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Boolean show = prefs.getBoolean("showNotification", true);
debug.postLog(Log.DEBUG, "Passive Service", "("+this.toString()+") showNotification: " + prefs.getBoolean("showNotification", true));
if(prefs.getBoolean("showNotification", true)){
I get the same result until the app is fully stopped then restarted, then the current value is kept. It is almost like the service gets a snapshot of the preferences.
What am I missing?
Solved, the service was running as remote.

Categories

Resources