Can a SharedPreferences.Editor be reused? - android

Can a SharedPreferences.Editor be safely reused? In other words, can I have this declared once in my class:
val editor = prefs.edit()
and then use its apply() method multiple times, like this?
editor.putString("myString", "Some string").apply()
// some time later...
editor.putInt("myInt", 682).apply()

Yes you can reuse it and then use its apply() method multiple times to save the values.
I see that you are using Kotlin, is the same as in Java/Android SDK.

Related

Shared Preferences is read as the wrong type

I'm reading SharedPreferences in my app at startup, and after a few runs it will crash and tell me that I'm trying to cast from a String to a Boolean. Below is the code that I use to read and write this value.
// Checks if the realm has been copied to the device, and copies it if it hasn't.
private void copyRealm() {
final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
if (!sharedPreferences.getBoolean(getString(R.string.pref_copied), false)) {
// Copy the realm to device.
final String path = copyBundledRealmFile(getResources().openRawResource(R.raw.realm), getString(R.string.realm_name));
// Save the path of the realm, and that the realm has been copied.
sharedPreferences.edit()
.putBoolean(getString(R.string.pref_copied), true)
.putString(getString(R.string.pref_path), path)
.apply();
}
}
The two strange things are that it doesn't start happening for a few builds, and so far it has only happened on a simulator. I haven't been able to check a physical device yet, but I've also been running this code without change for several months and had no trouble.
Why would I be getting this message?
Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Boolean
at android.app.SharedPreferencesImpl.getBoolean(SharedPreferencesImpl.java:293)?
Take a look at this question Android getDefaultSharedPreferences.
It seems it's a better idea to just use
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
or
SharedPreferences references1=getSharedPreferences("some_name",MODE_PRIVATE);
instead of using
SharedPreferences preferences= getDefaultSharedPreferences(this);
From the documentation:
getPreferences(MODE_PRIVATE) retrieves 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.
I regularly use one of these two approaches and had no problem of any kind so far.

Not getting value from Shared Preferences instantly

I am storing the data in the Shared Preferences by
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("menu_bar","abcd");
editor.apply();
and I am fetching the data from Shared Preferences in fragment by
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
String name = preferences.getString("menu_bar","");
if(!name.equalsIgnoreCase("")){
Toast.makeText(getActivity(), name, Toast.LENGTH_SHORT).show();
It is working when the app is removed from the stack.
But on the first time it is not working. Getting NULL in the first time but working fine from the second time. I also tried with editor.commit() when saving it.
Use getSharedPreferences("MyPref", Context.MODE_PRIVATE) and then commit to reflect changes instantly
SharedPreferences preferences = getSharedPreferences("MyPref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("menu_bar","abcd");
editor.commit();
Official Documentation
Commit your preferences changes back from this Editor to the SharedPreferences object it is editing. This atomically performs the requested modifications, replacing whatever is currently in the SharedPreferences.
Note that when two editors are modifying preferences at the same time, the last one to call apply wins.
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. If another editor on this SharedPreferences does a regular commit() while a apply() is still outstanding, the commit() will block until all async commits are completed as well as the commit itself.
As SharedPreferences instances are singletons within a process, it's safe to replace any instance of commit() with apply() if you were already ignoring the return value.
You don't need to worry about Android component lifecycles and their interaction with apply() writing to disk. The framework makes sure in-flight disk writes from apply() complete before switching states.
The SharedPreferences.Editor interface isn't expected to be implemented directly. However, if you previously did implement it and are now getting errors about missing apply(), you can simply call commit() from apply().
Try using the same instance of SharedPreferences. Easiest would be an explicitly named one:
class MyActivity {
private static final String PREFS_NAME = "myActivityPrefs";
private static SharedPreferences sharedPrefs = null;
public static SharedPreferences prefs(Context context) {
if (sharedPrefs == null) {
sharedPrefs = context.getSharedPreferences(PREFS_NAME, 0);
}
return sharedPrefs;
}
}
You then use it in the activity like this:
prefs(this).edit().putString("menu_bar","abcd").apply()
And in the fragment:
String name = MyActivity.prefs(getActivity()).getString("menu_bar","");
This is a recommended mode of operation that would give you good performance without waiting for I/O on your main thread - apply() does that for you but requires using the same instance to be consistent.
To use separate instances (sometimes you're forced to - for example through separate processes) always use commit(), which can freeze your main thread at times, and still doesn't guarantee consistency due to how filesystems work, I've seen instances where commit()ed data wasn't immediately available to a separate process, often on specific devices that had a FS configuration quirk.

Use SharedPreferences on multi-process mode

I've defined an instance of SharedPreferences that used on multi-process mode.
public class Prefs {
private static SharedPreferences prefs;
private static SharedPreferences.Editor editor;
private static void init(Context context) {
prefs = context.getSharedPreferences("alaki",
Context.MODE_MULTI_PROCESS);
editor = prefs.edit();
}
// static methods to set and get preferences
}
Now I'm using this class on a service with separate process and also in my main application process in static way.
Everything is going well, but sometimes all stored data on SharedPreferences instance removed!
How can I solve this problem?
Edit:
Finally I've solved my problem using by IPC.
There is currently no way of safely accessing SharedPreferences on multiple processes, as described in its documentation.
Note: This class does not support use across multiple processes.
After testing a lot with MODE_MULTI_PROCESS, I've three trials to share:
1- Initialize the SharedPreferences once in each process and use it multiple times.
The problem: The values are not reflected in each process as expected. So each process has its own value of the SharedPreferences.
2- Initialize the SharedPreferences in each put or get.
This actually works and the value now is interchangeable between processes.
The problem: sometimes after aggressively accessing the sharedpref, the shared preferences file got deleted with all its content, as described in this issue, and I get this warning in the log:
W/FileUtils﹕ Failed to chmod(/data/data/com.hegazy.multiprocesssharedpref/shared_prefs/myprefs.xml): android.system.ErrnoException: chmod failed: ENOENT (No such file or directory)
You can find why this happens in the issue.
3- Use synchronization to lock the methods that put and get values in the SharedPreferences.
This is completely wrong; synchronization doesn't work across processes. The SharedPreferences is actually using synchronization in its implementation, but that only ensures thread safety, not process safety. This is described very well here.
SharedPreferences itself is not process-safe. That's probably why SharedPreferences documentation says
Note: currently this class does not support use across multiple processes. This will be added later.
I've worked around this by combining:
Providing each process mutually-exclusive access to the SharedPreferences file (such as by using a socket-based locking mechanism)
Re-initialising the SharedPreferences with the MODE_MULTI_PROCESS flag every time you want to use it to bypass in-memory caching
This seems to work OK, but it hasn't been thoroughly tested in the real world, so I don't know if it's perfectly reliable.
You can see a working example I wrote here.
Warning: Looks like MODE_MULTI_PROCESS has been deprecated in Android M. It might stop working in the future.
Using the commit() method store the changes in persistent storage, hence it is slow and would make conflict across multiple call from other processes.
However there is an alternative to this method, you should call the apply() method, this method stores the changes in memory and then in disk storage asynchronously, so it is more reliable.
recalls that the use of context objects as static field, you have the risk of leakage of context because not declare the object in the application class
public class CustomApplication extends Application{
private Prefs prefs;
public void onCreate(){
prefs = new Prefs(this);
}
public Prefs getPrefs(){
return prefs;
}
}
From any context you can get the prefs
((MyApplication)context.getApplicationContext()).getPrefs();
Use a Content Provider which uses SharedPreferences. Example see here: https://github.com/hamsterksu/MultiprocessPreferences
public static int getValore(Context ctx, String contenitore, String chiave, int valore){
try {
SharedPreferences sh = ctx.getApplicationContext()
.getSharedPreferences(contenitore, Context.MODE_MULTI_PROCESS);
//SharedPreferences.Editor editor = sh.edit();
return sh.getInt(chiave, valore);
}catch (Exception ex){
return valore;
}
}
If two processes write data to SharedPreferences, then it might possible all SharedPreferences are reset to default values.
Also you can try to call clear() on the editor before storing val
SharedPreferences.Editor sp = settings.edit();
sp.clear();
sp.putString("Name", "YourName");
sp.commit();

Can I get data from shared preferences inside a service?

I'm developing an android application. I'm using android 2.2
In my application I am capturing GPS data and sending it to service with the 1 hour time interval. If user exits from application it's also working (it is required).
I'm using 2 services (User defined), one for capturing GPS data and other for sending to the server.
Here my doubt
In service, can we use shared preferences.
If we store any data in shared preferences in any activity of the application, will we be able to use that data in service with the help of shared preferences?
You can access the default shared preferences instance, which is shared across all your Activity and Service classes, by calling PreferenceManager.getDefaultSharedPreferences(Context context):
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
This is great for storing simple primitives (like booleans) or serializable objects. However, if you're capturing a lot of location data, you might consider using a SQLite database instead.
I find the solution.
Inside a service we call the following method to get the shared preferences
myapp.bmodel.getApplicationContext().getSharedPreferences("myPrefs_capture_gps_per_hour", Context.MODE_PRIVATE);
In the above code myapp is a object of the application class which is derived from Application
You need a context to get access to shared preferences. The best way is to create MyApplication as a descendant of Application class, instantiate there the preferences and use them in the rest of your application as MyApplication.preferences:
public class MyApplication extends Application {
public static SharedPreferences preferences;
#Override
public void onCreate() {
super.onCreate();
preferences = getSharedPreferences( getPackageName() + "_preferences", MODE_PRIVATE);
For example, if you need access to your preferences somewhere else, you may call this to read preferences:
String str = MyApplication.preferences.getString( KEY, DEFAULT );
Or you may call this to save something to the preferences:
MyApplication.preferences.edit().putString( KEY, VALUE ).commit();
(don't forget to call commit() after adding or changing preferences!)
Yes Shivkumar, you can use your share preferences in any kind of services as normal as you are using in your Activity.
same like
SharedPreferences preferences = getSharedPreferences("<PrefName>",
MODE_PRIVATE);
There are two ways to create instance of SharedPreference:
Case 1:
SharedPreferences preferences = activity.getSharedPreferences("<PrefName>", MODE_PRIVATE);
Case 2:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Notice if you create a preference with the same name (case 1) or same context (case 2) even at different places, it's still the same, and can share data, obviously.

How to delete shared preferences data from App in Android

How do I delete SharedPreferences data for my application?
I'm creating an application that uses a lot of web services to sync data. For testing purposes, I need to wipe out some SharedPreferences values when I restart the app.
To remove specific values: SharedPreferences.Editor.remove() followed by a commit()
To remove them all SharedPreferences.Editor.clear() followed by a commit()
If you don't care about the return value and you're using this from your application's main thread, consider using apply() instead.
My solution:
SharedPreferences preferences = getSharedPreferences("Mypref", 0);
preferences.edit().remove("text").commit();
Removing all preferences:
SharedPreferences settings = context.getSharedPreferences("PreferencesName", Context.MODE_PRIVATE);
settings.edit().clear().commit();
Removing single preference:
SharedPreferences settings = context.getSharedPreferences("PreferencesName", Context.MODE_PRIVATE);
settings.edit().remove("KeyName").commit();
If it's not necessary to be removed every time, you can remove it manually from:
Settings -> Applications -> Manage applications -> (choose your app)
-> Clear data or Uninstall
Newer versions of Android:
Settings -> Applications -> (choose your app) -> Storage -> Clear data
and Clear cache
Deleting Android Shared Preferences in one line :-)
context.getSharedPreferences("YOUR_PREFS", 0).edit().clear().commit();
Or apply for non-blocking asynchronous operation:
this.getSharedPreferences("YOUR_PREFS", 0).edit().clear().apply();
Seems that all solution is not completely working or out-dead
to clear all SharedPreferences in an Activity
PreferenceManager.getDefaultSharedPreferences(getBaseContext()).edit().clear().apply();
Call this from the Main Activity after onCreate
note* i used .apply() instead of .commit(), you are free to choose commit();
As of API 24 (Nougat) you can just do:
context.deleteSharedPreferences("YOUR_PREFS");
However, there is no backward compatibility, so if you're supporting anything less than 24, stick with:
context.getSharedPreferences("YOUR_PREFS", Context.MODE_PRIVATE).edit().clear().apply();
In the class definitions:
private static final String PREFERENCES = "shared_prefs";
private static final SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(PREFERENCES, MODE_PRIVATE);
Inside the class:
public static void deleteAllSharedPrefs(){
sharedPreferences.edit().clear().commit();
}
You can use the adb shell to do this even without a rooted phone. The only catch is that the app must be debuggable.
run-as <your package name> <command>
For example:
run-as com.asdf.blah rm /data/data/com.asdf.blah/databases/myDB.db
Alternatively, you can just do the above but without the command which will direct you to the app package root and allow you to execute more commands in the app's context.
Editor editor = getSharedPreferences("clear_cache", Context.MODE_PRIVATE).edit();
editor.clear();
editor.commit();
You can also just manually uninstall your app using your device. Then when you re-install your app, shared preferences have been reset.
Clear them all:
PreferenceManager.getDefaultSharedPreferences(context).edit().clear().apply()
Try this code:
SharedPreferences sharedPreferences = getSharedPreferences("fake", Context.MODE_PRIVATE);
SharedPreferences.Editor edit = sharedPreferences.edit();
edit.clear().commit();
If it is for your testing. You can use adb commands.
adb shell pm clear <package name>
For Kotlin users it is fairly easy:
val sharedPref = context.getSharedPreferences("myPref", Context.MODE_PRIVATE)
sharedPref.edit().clear().apply()
You can always do it programmatically as suggested by the other answers over here. But for development purpose, I find this Plugin very helpful as it speeds up my development significantly.
PLUGIN: ADB Idea
It provides you with features to Clear App Data and Revoke Permission from your Android Studio itself, just with click of a button.
String prefTag = "someTag";
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(applicationContext);
prefs.edit().remove(prefTag).commit();
This will delete the saved shared preferences with the name "someTag".
To remove the key-value pairs from preference, you can easily do the following
getActivity().getSharedPreference().edit().remove("key").apply();
I have also developed a library for easy manipulation of shared preferences. You may find the following link
https://github.com/farruhha/SimplePrefs
To clear all SharedPreferences centrally from any class:
public static SharedPreferences.Editor getEditor(Context context) {
return getPreferences(context).edit();
}
And then from any class: (commit returns a Boolean where you can check whether your Preferences cleared or not)
Navigation.getEditor(this).clear().commit();
Or you can use apply; it returns void
Navigation.getEditor(this).clear().apply();
To remove a particular value,
SharedPreferences.Editor remove(String key) followed by a commit() or a apply()
To remove all the values,
SharedPreferences.Editor clear() followed by a commit() or a apply()
The Kotlin ktx way to clear all preferences:
val prefs: SharedPreferences = getSharedPreferences("prefsName", Context.MODE_PRIVATE)
prefs.edit(commit = true) {
clear()
}
Click here for all Shared preferences operations with examples
None of the answers work for me since I have many shared preferences keys.
Let's say you are running an Android Test instead of a unit test.
It is working for me loop and delete through all the shared_prefs files.
#BeforeClass will run before all the tests and ActivityTestRule
#BeforeClass
public static void setUp() {
Context context = InstrumentationRegistry.getTargetContext();
File root = context.getFilesDir().getParentFile();
String[] sharedPreferencesFileNames = new File(root, "shared_prefs").list();
for (String fileName : sharedPreferencesFileNames) {
context.getSharedPreferences(fileName.replace(".xml", ""), Context.MODE_PRIVATE).edit().clear().commit();
}
}
One line of code in kotlin:
getSharedPreferences("MY_PREFS_NAME", MODE_PRIVATE).edit().clear().apply()
new File(context.getFilesDir(), fileName).delete();
I can delete file in shared preferences with it
My Answer:
In Java:
SharedPreferences myPrefs = context.getSharedPreferences("My_Pref", Context.MODE_PRIVATE);
myPrefs.edit().remove("my_key").apply();
In Kotlin:
val myPrefs = context.getSharedPreferences("My_Pref", Context.MODE_PRIVATE)
myPrefs.edit().remove("my_key").apply()
Kotlin :
var prefs2: SharedPreferences? = context!!.getSharedPreferences("loginFB", 0)
prefs2!!.edit().remove("email").commit()
This is my Kotlin method:
public fun clearAllSharedPrefs() {
val sharedPreferences: SharedPreferences = MainApplication.applicationContext()
.getSharedPreferences("MY_CUSTOME_KEY", Context.MODE_PRIVATE)
sharedPreferences.edit().clear()
sharedPreferences.edit().apply()
}
You can use preferences.edit().remove("key").commit() to delete saved values from shared preferences.
Just did this this morning. From a command prompt:
adb shell
cd /data/data/YOUR_PACKAGE_NAME/shared_prefs
rm * // to remove all shared preference files
rm YOUR_PREFS_NAME.xml // to remove a specific shared preference file
NOTE: This requires a rooted device such as the stock Android virtual devices, a Genymotion device, or an actual rooted handset/tablet, etc.

Categories

Resources