Shared preference is not working with android lockscreen - android

I have modified the default android lock screen with some tweaks .
I have use a shared preference in the lock screen to show an overlay text when the phone is booting for the first time . I am getting the overlay in first boot and saving the shared preference value to false . And throughout that session i am able to read the value of the shared preference . But when i restart the phone it seems like the shared preference is resetting
private Boolean mShowOverlay;
private final String SHOW_OVERLAY = "showoverlay";
private SharedPreferences myPrefs ;
myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
mShowOverlay = myPrefs.getBoolean(SHOW_OVERLAY, true);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putBoolean(SHOW_OVERLAY, false);
prefsEditor.commit();

Are you sure you are committing the SharedPreference, I mean calling commit() method??

Related

How to maintain global static variable values after destroy app while using service in background

I'm working on a service in my app. I'm using some global variables values while running service in background when app destroy manually. But when i'm closing app, all variables become destroy.
How can I use these variables while app destroyed.
Any advise is highly appreciated.
Thanks
You can use Shared preferences. They are accessible across your application any time anywhere
First save the values before destroying the app.
SharedPreferences prefs= context.getSharedPreferences("MyValues", 0);
SharedPreferences.Editor saveValue = prefs.edit();
saveValue.putString("Key", "Value");
saveValue.commit();
Now you can get those values from any where.
SharedPreferences prefs= context.getSharedPreferences("MyValues", 0);
prefs.getString("key", "defaultValue");
When the App close your variables die, Use SharedPreferences if you want save and read smallthings!
for read:
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
int showed = sharedPref.getInt("var", 0);
for write:
SharedPreferences sharedPre2f = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPre2f.edit();
editor.putInt("var", 0);
editor.commit();

Trying to edit specific sharedpreferences from different activity

So I have an application and i am trying to get one activity's shared preferences from a different activity. I cant use defaultSharedPreferences. Here is my code:
thisd = ma.
getSharedPreferences(
user, Context.MODE_PRIVATE);
Where thisd is the shared preferences, user is the specific sharedpreferences, and ma is the instance of the activity that has the shared preferences. Right now in activity called AddNameActivity.
Shared Preferences are not specific to any activity. It is common across application.
In the File where you add a value to Shared Prefernces, add this code sample.
SharedPreferences prefs = getSharedPreferences("your_file_name", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("yourStringName", "this_is_the_saved_value");
editor.commit();
In the file where you want to read the value (may be second activity), add this code sample.
SharedPreferences prefs = getSharedPreferences("your_file_name",MODE_PRIVATE);
String string = prefs.getString("yourStringName","default_value");
You can use a default file to save/ read your preferences.
In that case, Just replace the first line of the two code snippets above by this:
SharedPreferences prefs = getDefaultSharedPreferences(getApplicationContext());

Service not saving SharedPreference for Main Activity?

I am using a service to download and retrieve a list of URL's and put them in a sharedpreference.
With this..
SharedPreference images_article = this.getSharedPreferences("images_articles", MODE_WORLD_READABLE);
editor.putString("article2", urlImage2);
editor.putString("article3", urlImage2);
editor.commit();
Then in my Main.Activity i pull the url's from preference.
SharedPreference images_article = this.getSharedPreferences("images_articles", MODE_WORLD_READABLE);
urlImage2 = images_article.getString("article2", "NO ARTICLE AVAILABLE");
urlImage3 = images_article.getString("article3", "NO ARTICLE URL AVAILABLE");
The only problem is for some reason it isnt going inside of the shared preference, because the Main activity is loading the OLD URL's that has now changed. But in the Service i log the url's being retrieved and they are updated but for some reason in the main activity it still loads the old one. and im retrieving them from the same preference.
Is there anything i am missing or a better way to do this? Any help would be great!!
I was running in to a similar issue with my SharedPreferences between my Activity and Service. I ended up not using the default and used my own set file name
in the activity and service I set
private static final String PREFERENCE_NAME = "MyPreferenceFileName";
Then to get the values:
SharedPreferences pref = getSharedPreferences(PREFERENCE_NAME, Activity.MODE_PRIVATE);
pref_checked = pref.getBoolean("checked", true);
and to set the values:
SharedPreferences pref = getSharedPreferences(PREFERENCE_NAME, Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("checked", value);
editor.commit();
This allowed me to use the same get and put logic in both my Service and Activity without any issues. I hope this helped.
This might be happening due to the different contexts you are accessing from. I am not very sure though, but you can try this :
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sp.edit();
Use this code, whenever you try to access SharedPreferences, that is, from both the Service and the Activity. That might solve your problem.
Using this in both the Activity and Service classes seems to work for me, as it should now be using the same Context to access the application SharedPreferences:
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

Saving facebook login details locally in android app

I am developing an Android app where the user has the facility of Facebook sharing. I have the login details of the user for the Facebook, now what I am trying to do is these login details should be saved until the application is not deleted.
When I tried to find the answer for this, I got some answers stating about shared preferences. But I am not cleared exactly how it works.
Here is what I am trying to do,
Username = username.getText().toString();
PassWord = password.getText().toString();
where username and password are 2 edittext fields. When the user enters for the first time into Facebook, I should save these data somewhere for my future reference so that he need not login again.
Can any one let me know how to achieve this?
// Save your info
SharedPreferences settings = getSharedPreferences("my_file_name", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("username", username.getText().toString());
editor.putString("password", password.getText().toString());
editor.commit();
// Obtain your info
SharedPreferences settings = getSharedPreferences("my_file_name", 0);
String username = settings.getString("username", "");
String password = settings.getString("password", "");
A file will be created in:
data/data/[your.package.path]/shared_prefs/[your.package.path]_preferences.xml
You can use sharedPreference for this.
Many applications may provide a way to capture user preferences on the settings of a specific application or an activity. For supporting this, Android provides a simple set of APIs.
Preferences are typically name value pairs. They can be stored as “Shared Preferences” across various activities in an application (note currently it cannot be shared across processes). Or it can be something that needs to be stored specific to an activity.
Shared Preferences: The shared preferences can be used by all the components (activities, services etc) off the applications.
Activity handled preferences: These preferences can only be used with in the activity and can not be used by other components of the application.
Shared Preferences:
The shared preferences are managed with the help of getSharedPreferences method of the Context class. The preferences are stored in a default file(1) or you can specify a file name(2) to be used to refer to the preferences.
(1) Here is how you get the instance when you specify the file name
public static final String PREF_FILE_NAME = "PrefFile";
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
MODE_PRIVATE is the operating mode for the preferences. It is the default mode and means the created file will be accessed by only the calling application. Other two mode supported are MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE. In MODE_WORLD_READABLE other application can read the created file but can not modify it. In case of MODE_WORLD_WRITEABLE other applications also have write permissions for the created file.
(2) The recommended way is to use by the default mode, without specifying the file name
SharedPreferences preferences = PreferencesManager.getDefaultSharedPreferences(context);
Finally, once you have the preferences instance, here is how you can retrieve the stored values from the preferences:
int storedPreference = preferences.getInt("storedInt", 0);
To store values in the preference file SharedPreference.Editor object has to be used. Editor is the nested interface of the SharedPreference class.
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
Editor also support methods like remove() and clear() to delete the preference value from the file.
Activity Preferences:
The shared preferences can be used by other application components. But if you do not need to share the preferences with other components and want to have activities private preferences. You can do that with the help of getPreferences() method of the activity. The getPreference method uses the getSharedPreferences() method with the name of the activity class for the preference file name.
Following is the code to get preferences
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);
The code to store values is also same as in case of shared preferences.
SharedPreferences preferences = getPreference(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
You can also use other methods like storing the activity state in database. Note Android also contains a package called android.preference. The package defines classes to implement application preferences UI.
Don't Use preferences to save facebook data:
Please use this code in Oncreate method:
if (isLoggedIn()) {
layout_after_fb_login.setVisibility(View.VISIBLE);
updateUI();
} else {
layout_after_fb_login.setVisibility(View.GONE);
}
////
private boolean isLoggedIn() {
AccessToken accesstoken = AccessToken.getCurrentAccessToken();
return !(accesstoken == null || accesstoken.getPermissions().isEmpty());
}
private void updateUI() {
Profile profile = Profile.getCurrentProfile();
if (null != profile) {
profilePictureView.setProfileId(profile.getId());
userNameView.setText(String.format("%s %s", profile.getFirstName(), profile.getLastName()));
layout_after_fb_login.setVisibility(View.VISIBLE);
} else {
layout_after_fb_login.setVisibility(View.GONE);
}
}

onSharedPreferenceChanged edit stored value?

If I have a onSharedPreferenceChanged event in my PreferenceActivity, that is checking if a CheckBoxPreference is checked or not and setting setEnabled on some other Preference, does the actual value of the other Preference get changed in the SharedPreferences, or do I have to manually set them?
What I have is:
public void onSharedPreferenceChanged(Settings sharedPreferences, String key)
{
CheckBoxPreference cbUpdatesEnabled = (CheckBoxPreference)getPreferenceScreen().findPreference("updatesenabled");
CheckBoxPreference cbVibrate = (CheckBoxPreference)getPreferenceScreen().findPreference("vibrate");
cbVibrate.setEnabled(cbUpdatesEnabled.isChecked());
}
Which toggles whether the "vibrate" checkbox is enabled or disabled in the UI, but then do I also have to use:
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("vibrate", cbUpdatesEnabled.isChecked());
editor.commit();
Or is there some other way of updating the SharedPreferences? It doesn't look like the value is automatically saved just based on if it's enabled or not.
You don't have to manually update the preference value if you are using PreferenceActivity.
For more information check following tutorials.
Click here
Click here

Categories

Resources