- Android — Storing/retrieving strings with shared preferences
- 7 Answers 7
- How do you save/store objects in SharedPreferences on Android?
- 22 Answers 22
- Save List of user-defined objects to SharedPreferences
- Get List of user-defined objects from SharedPreferences
- Update:
- Is it possible to add an array or object to SharedPreferences on Android
- 11 Answers 11
- How to Save ArrayList to SharedPreferences in Android?
- What we are going to build in this article?
- Step by Step Implementation
Android — Storing/retrieving strings with shared preferences
As the title says, I want to save and retrieve certain strings. But my code won’t pass through the first line neither in retrieve or store. I tried to follow this link: http://developer.android.com/guide/topics/data/data-storage.html
and my retrieve method:
lydliste is a static string array. PREFS_NAME is
7 Answers 7
To save to preferences:
To get a stored preference:
Where context is your Context.
If you are getting multiple values, it may be more efficient to reuse the same instance.
And if you are saving multiple values:
Note: Saving with apply() is better than using commit() . The only time you need commit() is if you require the return value, which is very rare.
I solved it! It didn’t work when I called the methods from within the class! I had to call it from another class for some reason, and write «classname.this» as Context parameter. Here’s the final working:
Simple steps to save a String with SharedPreferences:
try it with context:
If you do not care about the return value of commit() better use apply() as it being asynchronous is faster that 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. 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.
Источник
How do you save/store objects in SharedPreferences on Android?
I need to get user objects in many places, which contain many fields. After login, I want to save/store these user objects. How can we implement this kind of scenario?
I can’t store it like this:
«and executive Object«? Please check your grammar before posting on StackOverflow.
22 Answers 22
You can use gson.jar to store class objects into SharedPreferences. You can download this jar from google-gson
Or add the GSON dependency in your Gradle file:
you can find latest version here
Creating a shared preference:
To add to @MuhammadAamirALi’s answer, you can use Gson to save and retrieve a list of objects
Save List of user-defined objects to SharedPreferences
Get List of user-defined objects from SharedPreferences
I know this thread is bit old. But I’m going to post this anyway hoping it might help someone. We can store fields of any Object to shared preference by serializing the object to String. Here I have used GSON for storing any object to shared preference.
Save Object to Preference :
Retrieve Object from Preference:
Note :
Remember to add compile ‘com.google.code.gson:gson:2.6.2’ to dependencies in your gradle.
Example :
Update:
As @Sharp_Edge pointed out in comments, the above solution does not work with List .
A slight modification to the signature of getSavedObjectFromPreference() — from Class classType to Type classType will make this solution generalized. Modified function signature,
Better is to Make a global Constants class to save key or variables to fetch or save data.
To save data call this method to save data from every where.
Use it to get data.
and a method something like this will do the trick
Try this best way :
PreferenceConnector.java
Write the Value :
And Get value using :
You haven’t stated what you do with the prefsEditor object after this, but in order to persist the preference data, you also need to use:
You can save object in preferences without using any library, first of all your object class must implement Serializable:
Then you can easily use these two method to convert object to string and string to object:
See here, this can help you:
I had trouble using the accepted answer to access Shared Preference data across activities. In these steps, you give getSharedPreferences a name to access it.
Add the following dependency in the build.gradel (Module: app) file under Gradle Scripts:
To Save:
To Retrieve in a Different Activity:
hope this helps you 🙂
Step 1: Copy paste these two functions in your java file.
Step 2: to save use:
to retrieve use:
You can set different shared preferences by using different key names like:
there are two file solved your all problem about sharedpreferences
1)AppPersistence.java
2)AppPreference.java
now you can save,remove or get like,
-save
-remove
-get
If you want to store the whole Object that you get in response, It can achieve by doing something like,
First Create a method that converts your JSON into a string in your util class as below.
Then In Shared Preferences Class Do something like,
and then create a method for getPreferences
Then Just call the First method when you get response and second when you need to get data from share preferences like
Hope it will help you.
Happy Coding();
Here’s a take on using Kotlin Delegated Properties that I picked up from here, but expanded on and allows for a simple mechanism for getting/setting SharedPreference properties.
For String , Int , Long , Float or Boolean , it uses the standard SharePreference getter(s) and setter(s). However, for all other data classes, it uses GSON to serialize to a String , for the setter. Then deserializes to the data object, for the getter.
Similar to other solutions, this requires adding GSON as a dependency in your gradle file:
Here’s an example of a simple data class that we would want to be able to save and store to SharedPreferences:
Here is the one class that implements the property delegates:
Note: you shouldn’t need to update anything in the sealed class . The delegated properties are the Object/Singletons UserPreferenceProperty , NullableUserPreferenceProperty and FirstTimeUser .
To setup a new data object for saving/getting from SharedPreferences, it’s now as easy as adding four lines:
Finally, you can read/write values to SharedPreferences by just using the by keyword:
Источник
Is it possible to add an array or object to SharedPreferences on Android
I have an ArrayList of objects that have a name and an icon pointer and I want to save it in SharedPreferences . How can I do?
NOTE: I don’t want to use Database
11 Answers 11
SAVE ARRAY
LOAD ARRAY
So from the android developer site on Data Storage:
Shared preferences are not strictly for saving «user preferences,» such as what ringtone a user has chosen. If you’re interested in creating user preferences for your application, see PreferenceActivity, which provides an Activity framework for you to create user preferences, which will be automatically persisted (using shared preferences).
So I think it is okay since it is simply just key-value pairs which are persisted.
To the original poster, this is not that hard. You simply just iterate through your array list and add the items. In this example I use a map for simplicity but you can use an array list and change it appropriately:
You would do something similar to read the key-value pairs again. Let me know if this works.
Update: If you’re using API level 11 or later, there is a method to write out a String Set
Other way to do same:
Using GSON in Java:
Using GSON in Kotlin
Shared preferences introduced a getStringSet and putStringSet methods in API Level 11, but that’s not compatible with older versions of Android (which are still popular), and also is limited to sets of strings.
Android does not provide better methods, and looping over maps and arrays for saving and loading them is not very easy and clean, specially for arrays. But a better implementation isn’t that hard:
Now you can save any collection in shared preferences with this five methods. Working with JSONObject and JSONArray is very easy. You can use JSONArray (Collection copyFrom) public constructor to make a JSONArray out of any Java collection and use JSONArray ‘s get methods to access the elements.
There is no size limit for shared preferences (besides device’s storage limits), so these methods can work for most of usual cases where you want a quick and easy storage for some collection in your app. But JSON parsing happens here, and preferences in Android are stored as XMLs internally, so I recommend using other persistent data store mechanisms when you’re dealing with megabytes of data.
Easy mode for complex object storage with using Gson google library [1]
I loaded an array of waist sizes (already created in my array.xml) into my preferences.xml file with the code below. @array/pant_inch_size is the id of the entire array.
This populated the menu with choices from the array. I set the default size as 34, so when the menu pops up, they see size 34 is pre-selected.
The Simple way is, to convert it to JSON String as below example:
Then store the string in the shared preferences. Once you need it just get string from shared preferences and convert back to JSONArray or JSONObject(as per your requirement.)
This is the shared preferences code i use successfully, Refer this link:
You can use putStringSet
This allow you to save a HashSet in your preferences, just like this:
Save
Retrive
The putStringSet allow just a Set and this is an unordered list.
When I was bugged with this, I got the serializing solution where, you can serialize your string, But I came up with a hack as well.
Read this only if you haven’t read about serializing, else go down and read my hack
In order to store array items in order, we can serialize the array into a single string (by making a new class ObjectSerializer (copy the code from – www.androiddevcourse.com/objectserializer.html , replace everything except the package name))
Entering data in Shared preference :
the rest of the code on line 38 —
Put the next arg as this, so that if data is not retrieved it will return empty array(we cant put empty string coz the container/variable is an array not string)
Coming to my Hack :-
Merge contents of array into a single string by having some symbol in between each item and then split it using that symbol when retrieving it. Coz adding and retrieving String is easy with shared preferences. If you are worried about splitting just look up «splitting a string in java».
[Note: This works fine if the contents of your array is of primitive kind like string, int, float, etc. It will work for complex arrays which have its own structure, suppose a phone book, but the merging and splitting would become a bit complex. ]
PS: I am new to android, so don’t know if it is a good hack, so lemme know if you find better hacks.
Источник
How to Save ArrayList to SharedPreferences in Android?
SharedPreferences in Android is local storage that is used to store strings, integers, and variables in phone storage so that we can manage the state of the app. We have seen storing simple variables in shared prefs with key and value pair. In this article, we will see How we can store ArrayList to shared preferences in our Android app.
What we are going to build in this article?
We will be building a simple application in which we will be displaying course names with its description in a simple RecyclerView and we will be storing all this data in our shared preferences. So when we close our app and reopens our app all the data will be saved in shared preferences and the state of our recycler view is maintained. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step by Step Implementation
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Adding dependency for gson in build.gradle
Navigate to the app > Gradle Scripts > build.gradle(app) and add the below dependency in the dependencies section.
After adding this dependency sync your project.
Step 3: Creating a modal class for storing our data
Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name your class as CourseModal and add the below code to it.
Источник