Not getting saved SharedPreference value from IntentService - android

I'm creating a shared preference in my MainActivity and then I want to get a value saved in the shared preference in my IntentService; however; I keep getting the default value rather than the value that I had saved.
This is my code to create the SharedPreference in my MainActivity:
SharedPreferences prefs = this.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
prefs.edit().putString("inter", inter).apply();
And in my IntentService class:
protected void onHandleIntent(Intent intent) {
SharedPreferences preferences = getApplicationContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
final String inter = preferences.getString("inter", "default_no");
}

The problem here is a subtle one:
SharedPreferences.Editor#commit stores the modifications to storage in a blocking fashion, so you are guaranteed that any other instance that queries the value on the same thread will actually get the new one.
SharedPreferences.Editor#apply does so asynchronously so if you fetch the value on another instance of SharedPreferences too fast, it might not get the updated value.
Commit may actually work better on your situation as you are not doing any big change to the preferences. If you need to use apply, you might want to induce a slight delay using Handler#post.
Cheers.

Try using and editor to save your value in SharedPreferences
SharedPreferences pref = getApplicationContext().getSharedPreferences(PREFS_NAME, context.MODE_PRIVATE);
SharedPreferences.Editoreditor = pref.edit();
editor.putString("inter", inter);
editor.commit();//This will make your value store in SharedPreferences

Related

sharedpreferences value not updated

I have a Sharedpreferences to check if the user has activated the pro section with InAppPurchase and I check it every time Mainactivity is opens, like this:
SharedPreferences s = c.getSharedPreferences("app" , MODE_PRIVATE);
String value = s.getString(key , " ");
Log.i("myapp" , value);
and if some one tries to change the value manually my app warns him .so I tried to test my app's security and changed the value manually with text editor from data/data/com.myapp.package/shared_prefs/ let's say the value was 39m49ur3.I changed it a to 87mjr83.Then I started the app and the value from the logs stil was 39m49ur3 . I closed the app and started it again but no change was seen except when I clear the RAM of my device then start the app , finally then the value I got from the logs is what really is in the shared_prefs folder.
What can I do about this?
Save like this,
SharedPreferences pref = c.getSharedPreferences("app", MODE_PRIVATE);
Editor editor = pref.edit();
editor.putString("myapp", "string value");
editor.commit();
Get Like this,
pref.getString("myapp", null);
//to save String in shared preferences
public void put(String key, String value) {
mSharedPreferences.edit().putString(key, value).apply();
}
//to get value from shared preferences
public String get(String key, String defaultValue) {
return mSharedPreferences.getString(key, defaultValue);
}
Try to use
editor.apply();
Instead of
editor.commit();
Unlike commit(), which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures.

Shared Preferences issue, not freeing the value after calling clear

In my application I want to clear SharedPreferences on button click. This is what I'm using for storing values in it:
SharedPreferences clearNotificationSP = getSharedPreferences("notification_prefs", 0);
SharedPreferences.Editor Notificationeditor = clearNotificationSP.edit();
Notificationeditor.putString("notificationCount", notificationCountValue);
Notificationeditor.commit();
And the following code on onClick():
SharedPreferences clearedNotificationSP = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editorSP = clearedNotificationSP.edit();
editorSP.remove("notificationCount");
editorSP.commit();
System.out.println("Saved in SP clearedNotification: "+ clearNotification);
I was printing the value after clearing it but still I was getting the same value.
What am I missing?
Any kind of help will be appreciated.
getDefaultSharedPreferences and getSharedPreferences("notification_prefs", );
returns two different SharedPreferences. Since you are adding notificationCount inside notification_prefs, you should retrieve SharedPreference with getSharedPreferences("notification_prefs", );
getDefaultSharedPreferences uses a default preference-file name, while getSharedPreferences use the filename you provided as paramter

Shared Preferences in Android?

I'm a novice Android developer who are currently trying hard to build a Login Screen.
I need to find the easiest way to store the username and password in 1 class and retrieve it from another class. See Google has provided several ways: http://developer.android.com/guide/topics/data/data-storage.html
which one is the most efficient and easy to code?
thanks!
For Login screen tasks like storing username and password you can use Shared Preferences. Here I had made custom methods for using shared preferences. Call savePreferences() method and put your Key and Value(as savePreferences() is based on XML), similarly call Load with your Key. And lastly don't forgot to call deletePreferences() on LOGOUT.
/**
* Method used to get Shared Preferences */
public SharedPreferences getPreferences()
{
return getSharedPreferences(<PREFRENCE_FILE_NAME>, MODE_PRIVATE);
}
/**
* Method used to save Preferences */
public void savePreferences(String key, String value)
{
SharedPreferences sharedPreferences = getPreferences();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
/**
* Method used to load Preferences */
public String loadPreferences(String key)
{
try {
SharedPreferences sharedPreferences = getPreferences();
String strSavedMemo = sharedPreferences.getString(key, "");
return strSavedMemo;
} catch (NullPointerException nullPointerException)
{
Log.e("Error caused at TelaSketchUtin loadPreferences method",
">======>" + nullPointerException);
return null;
}
}
/**
* Method used to delete Preferences */
public boolean deletePreferences(String key)
{
SharedPreferences.Editor editor=getPreferences().edit();
editor.remove(key).commit();
return false;
}
Define some statics to store the preference file name and the keys you're going to use:
public static final String PREFS_NAME = "MyPrefsFile";
private static final String PREF_USERNAME = "username";
private static final String PREF_PASSWORD = "password";
You'd then save the username and password as follows:
getSharedPreferences(PREFS_NAME,MODE_PRIVATE)
.edit()
.putString(PREF_USERNAME, username)
.putString(PREF_PASSWORD, password)
.commit();
So you would retrieve them like this:
SharedPreferences pref = getSharedPreferences(PREFS_NAME,MODE_PRIVATE);
String username = pref.getString(PREF_USERNAME, null);
String password = pref.getString(PREF_PASSWORD, null);
if (username == null || password == null) {
//Prompt for username and password
}
Alternatively, if you don't want to name a preferences file you can just use the default:
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
For your purpose both, SQLite Database and SharedPreferences will work. But I would suggest SharedPreferences as they are very easy to use. Some ppl like to create a class to hold variables like this but the benefit of SQLite and SharedPreferences file is that the user login name and password information will be with you even if the app goes in background and gets destroyed. So when the user comes back to your app, you can sign them in again without asking for password. If user explicitly decides to logout, you can simply remove the login information from shared preferences file
The easiest way of retrieving log in information from other activities is using "SharedPreferences". I strongly recommend this method for storage and retrieval of Username and Password. Because you can access this information from anywhere in the application without any complications. The log in information may have to use repeatedly in an application.
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 the 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 = PreferenceManager.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.
To see some more examples check Android's Data Storage post on developers site.
For more info, check this link:
Making data persistent in android

Trouble using sharedPreferences between two activities

I am trying to save a date in one activity and then have that date put in a textView in another activity. I am not sure about how to get the two activities to communicate with each other.
In file called report.java I have this method that gets the date and save it in sharedPrefernces.
private void updateLabel() {
date.setText(fmtDate.format(dateAndTime.getTime()));
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("date", date.getText().toString()); // value to store
editor.commit();
}
I am trying to figure out how to get my file called inspection use this to populate a textView
The problem I think I am having is with getting the correct name for the report file.
public static final String PREF_FILE_NAME = "report";
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
then I have this code on a method called onResume()
#Override
public void onResume() {
super.onResume();
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
String strDate=preferences.getString("date", date.getText().toString());
date.setText(strDate);
}
You are saving the value to two seperate preference files.
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
Use only one.
Why not use the default preference file that is accessible by all classes/activities of your app?
SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(yourContext);
preferences.edit().putString(YOURKEY, yourStrValue);
This way you are not creating extra preference files in your app that you have to remember which values are stored in which files. Definately makes life easier.

Data cache in Shared Preference

I have 2 processes in my application. From one process i save data in to SharedPreferences.
From second process - retrieve. When i retrieve data, i receive SharedPreferences with old data(i check xml file and see, that currently data in file and data that was received are different). It looks like this data was cached. I changed saving methods (commit/apply) but no result.
PS: just for example http://pastebin.com/Zx2ffvSg
//saving
{ ...
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString(MY_NAME, "Sai");
prefsEditor.putString(MY_WALLPAPER, "f664.PNG");
prefsEditor.commit();
... }
//retrieving
// when i call getData() I put "this" as argument.
public void getData(Context context){
SharedPreferences myPrefs = context.getSharedPreferences("myPrefs", MODE_PRIVATE);
...}
The solution is add to neccesary flags Context.MODE_MULTI_PROCESS flag when open shared preference (Available in API Level 11 and up)

Categories

Resources