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.
Related
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.
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.
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();
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.
I recently coded an Android app. It's just a simple app that allows you to keep score of a basketball game with a few simple counter intervals. I'm getting demand to add a save feature, so you can save your scores and then load them back up. Currently, when you stop the app, your data is lost. So what I was wondering is what I would have to add to have the app save a label (score) and then load it back up. Thanks guys sorry I don't know much about this stuff.
You have two options, and I'll leave selection up to you.
Shared Preferences
This is a framework unique to Android that allows you to store primitive values (such as int, boolean, and String, although strictly speaking String isn't a primitive) in a key-value framework. This means that you give a value a name, say, "homeScore" and store the value to this key.
SharedPreferences settings = getApplicationContext().getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("homeScore", YOUR_HOME_SCORE);
// Apply the edits!
editor.apply();
// Get from the SharedPreferences
SharedPreferences settings = getApplicationContext().getSharedPreferences(PREFS_NAME, 0);
int homeScore = settings.getInt("homeScore", 0);
Internal Storage
This, in my opinion, is what you might be looking for. You can store anything you want to a file, so this gives you more flexibility. However, the process can be trickier because everything will be stored as bytes, and that means you have to be careful to keep your read and write processes working together.
int homeScore;
byte[] homeScoreBytes;
homeScoreBytes[0] = (byte) homeScore;
homeScoreBytes[1] = (byte) (homeScore >> 8); //you can probably skip these two
homeScoreBytes[2] = (byte) (homeScore >> 16); //lines, because I've never seen a
//basketball score above 128, it's
//such a rare occurance.
FileOutputStream outputStream = getApplicationContext().openFileOutput(FILENAME, Context.MODE_PRIVATE);
outputStream.write(homeScoreBytes);
outputStream.close();
Now, you can also look into External Storage, but I don't recommend that in this particular case, because the external storage might not be there later. (Note that if you pick this, it requires a permission)
OP is asking for a "save" function, which is more than just preserving data across executions of the program (which you must do for the app to be worth anything.)
I recommend saving the data in a file on the sdcard which allows you to not only recall it later, but allows the user to mount the device as an external drive on their own computer and grab the data for use in other places.
So you really need a multi-point system:
1) Implement onSaveInstanceState(). In this method, you're passed a Bundle, which is basically like a dictionary. Store as much information in the bundle as would be needed to restart the app exactly where it left off. In your onCreate() method, check for the passed-in bundle to be non-null, and if so, restore the state from the bundle.
2) Implement onPause(). In this method, create a SharedPreferences editor and use it to save whatever state you need to start the app up next time. This mainly consists of the users' preferences (hence the name), but anything else relavent to the app's start-up state should go here as well. I would not store scores here, just the stuff you need to restart the app. Then, in onCreate(), whenever there's no bundle object, use the SharedPreferences interface to recall those settings.
3a) As for things like scores, you could follow Mathias's advice above and store the scores in the directory returned in getFilesDir(), using openFileOutput(), etc. I think this directory is private to the app and lives in main storage, meaning that other apps and the user would not be able to access the data. If that's ok with you, then this is probably the way to go.
3b) If you do want other apps or the user to have direct access to the data, or if the data is going to be very large, then the sdcard is the way to go. Pick a directory name like com/user1446371/basketballapp/ to avoid collisions with other applications (unless you're sure that your app name is reasonably unique) and create that directory on the sdcard. As Mathias pointed out, you should first confirm that the sdcard is mounted.
File sdcard = Environment.getExternalStorageDirectory();
if( sdcard == null || !sdcard.isDirectory()) {
fail("sdcard not available");
}
File datadir = new File(sdcard, "com/user1446371/basketballapp/");
if( !datadir.exists() && !datadir.mkdirs() ) {
fail("unable to create data directory");
}
if( !datadir.isDirectory() ) {
fail("exists, but is not a directory");
}
// Now use regular java I/O to read and write files to data directory
I recommend simple CSV files for your data, so that other applications can read them easily.
Obviously, you'll have to write activities that allow "save" and "open" dialogs. I generally just make calls to the openintents file manager and let it do the work. This requires that your users install the openintents file manager to make use of these features, however.
In onCreate:
SharedPreferences sharedPref = getSharedPreferences("mySettings", MODE_PRIVATE);
String mySetting = sharedPref.getString("mySetting", null);
In onDestroy or equivalent:
SharedPreferences sharedPref = getSharedPreferences("mySettings", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("mySetting", "Hello Android");
editor.commit();
Use SharedPreferences, http://developer.android.com/reference/android/content/SharedPreferences.html
Here's a sample:
http://developer.android.com/guide/topics/data/data-storage.html#pref
If the data structure is more complex or the data is large, use an Sqlite database; but for small amount of data and with a very simple data structure, I'd say, SharedPrefs will do and a DB might be overhead.
There is a lot of options to store your data and Android offers you to chose anyone
Your data storage options are the following:
Shared Preferences
Store private primitive data in key-value pairs.
Internal Storage
Store private data on the device memory.
External Storage
Store public data on the shared external storage.
SQLite Databases
Store structured data in a private database.
Network Connection
Store data on the web with your own network server
Check here for examples and tuto
2021 Answer
Old question but in 2021 you can use several things to save data.
1. Using local database - Room Library
Room is a library that let you store data in the internal SqlLite database that come with your Android device, it's a local database. It's easy and really powerful.
https://developer.android.com/training/data-storage/room
2. Using a remote database - Firebase / Your own database implementation
You can use Firebase services or your own database implementation on your server to remote store your data, that way you could access the data throw multiple devices.
https://firebase.google.com/docs/firestore
3. Storing a local file
You can store all information in a local file saved in the device's external storage, using maybe a .txt file with a \n as data separator. That option looks really "caveman" in 2021.
https://stackoverflow.com/a/14377185/14327871
4. Using SharedPreferences
As many people pointed you can also use the sharedPreferences to store little information as pair of key - value, it's useful for example when saving user preferences across a session.
https://developer.android.com/training/data-storage/shared-preferences?hl=en
For the OP case I would suggest using the 1st or 2nd option.
Shared preferences:
android shared preferences example for high scores?
Does your application has an access to the "external Storage Media". If it does then you can simply write the value (store it with timestamp) in a file and save it. The timestamp will help you in showing progress if thats what you are looking for. {not a smart solution.}
You can store your scores and load them back easily! by using this method
Use this library Paper Db
Add this library on your app:
implementation 'io.github.pilgr:paperdb:2.7.1'
and then initialize it once in the activity onCreate() you are storing:
Paper.init(context)
create a key to store your scores
int myScore=10;
Paper.book().write("scores", myScore);
and get the value of the score :
int mySavedScores=Paper.book().read("scores");
that's It!!! now you can save and access the value even application is closed
and refer the documentation for more methods and information,
it's a Good habit to read the documentation.
Please don't forget one thing - Internal Storage data are deleted when you uninstall the app. In some cases it can be "unexpected feature". Then it's good to use external storage.
Google docs about storage - Please look in particular at getExternalStoragePublicDirectory
Quick answer:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Boolean Music;
public static final String PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//restore preferences
SharedPreferences settings = this.getSharedPreferences(PREFS_NAME, 0);
Music = settings.getBoolean("key", true);
}
#Override
public void onClick() {
//save music setup to system
SharedPreferences settings = this.getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("key", Music);
editor.apply();
}
}
In my opinion db4o is the easiest way to go.
Here you can find a tutorial:
http://community.versant.com/documentation/reference/db4o-7.12/java/tutorial/
And here you can download the library:
http://www.db4o.com/community/download.aspx?file=db4o-8.0-java.zip
(Just put the db4o-8.0...-all-java5.jar in the lib directory into your project's libs folder.
If there is no libs folder in you project create it)
As db4o is a object oriented database system you can directly save you objects into the database and later get them back.
use this methods to use sharedPreferences very easily.
private val sharedPreferences = context.getSharedPreferences("myPreferences", Context.MODE_PRIVATE)
fun put(key: String, value: String) = sharedPreferences.edit().putString(key, value).apply()
fun put(key: String, value: Int) = sharedPreferences.edit().putInt(key, value).apply()
fun put(key: String, value: Float) = sharedPreferences.edit().putFloat(key, value).apply()
fun put(key: String, value: Boolean) = sharedPreferences.edit().putBoolean(key, value).apply()
fun put(key: String, value: Long) = sharedPreferences.edit().putLong(key, value).apply()
fun getString(key: String, defaultValue: String? = null): String? = sharedPreferences.getString(key, defaultValue)
fun getInt(key: String, defaultValue: Int = -1): Int = sharedPreferences.getInt(key, defaultValue)
fun getFloat(key: String, defaultValue: Float = -1F): Float = sharedPreferences.getFloat(key, defaultValue)
fun getBoolean(key: String, defaultValue: Boolean = false): Boolean = sharedPreferences.getBoolean(key, defaultValue)
fun getLong(key: String, defaultValue: Long = -1L): Long = sharedPreferences.getLong(key, defaultValue)
fun clearAll() = sharedPreferences.edit().clear().apply()
put them in a class and get context in its constructor.