Save Arraylist of custom objects SharedPreferences - java

I am really confused about how to save my ArrayList of custom objects into SharedPreference. I looked up a very popular thread but did not understand solution as certain variables were not given context. My arraylist has certain things like Strings, UUIDs, and Dates, and I do not mind going to API 11 to avoid using gson or json. If someone were to be so kind as to explain the solution in this or provide their own I would really appreciate. I am new to this, been doing for a couple of months and want to make sure I understand everything in depth but my english is not so well. Thank you in advance!

Serialize that arraylist and store it in sharedPreference.
Profile profile = myProfile;
String serializedData = profile .serialize();
SharedPreferences.Editor editor = prefs.edit();
editor.putString("Profile", serializedData);
editor.apply();
For Deserialize
String profileSerialized = prefs.getString("Profile", "");
profile = Profile.create(profileSerialized);

I would look into storing the data into a SQLiteDatabase. SharedPreferences wasn't intended to save custom objects. If you really want to use SharedPreferences then Gson will be the best solution. API 11 added the ability to save a list of strings, not objects.

Related

Best place to store custom objects so all activities can see them

I am an iOS developer who is trying to learn Android and I would like to make sure that I am following best practices.
I have custom objects that need to be accessible by 1 -> m activities and they need to be saved when the application closes. Currently I am using SharedPreferences, code below, to save them but I am not sure if it is the best route. Should I be using a singleton? Is there a better way?
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(userProfile);
prefsEditor.putString("UserProfile", json);
prefsEditor.commit();
gson = new Gson();
json = mPrefs.getString("UserProfile", "");
UserProfileObject outObject = gson.fromJson(json, UserProfileObject.class);
A singleton won't be saved when the application exits. Really your options are:
*SharedPreferences. Good for a small number of key/value pairs
*Database. Good for relational data
*File on disk, in whatever format you prefer. Good for any amount of data, but you may need to write a custom parser.
Storing json in a shared preference is a bit weird. Its not horrible so long as you aren't storing a lot of keys in there, but it makes it seem like you didn't know how to write a file.
#Gabe has provided a good answer. I am adding my 2 cents to it
I personally do not like to save serialised data in SharedPreferences. Instead I would use local db storage such as SQLite or Realm to store it. The reason being serialisation/deserialisation involves marshalling/unmarshalling objects using reflection which could potentially hit performance in a negative way.
In short, Use local db for storing complex / relational data and SharedPreferences for storing simple data
I think if your UserProfileObject can be easily constructed from Json and it doesn't contain any sensitive data (i.e. password), might be fine just having it in SharedPreferences (just save the json string like what you are doing).
Using a singleton SessionManager / ProfileManager class with that should be sufficient enough. Even though it might be used by 1 -> m activities, it only hits the SharedPreferences once using the singleton. Just make sure you keep the copy of the data in the singleton and in SharedPreferences in sync when there are changes. Or just dump the singleton all together and hit the SharedPreferences every time you need it (less worries about keeping copies in sync), don't think your use case will hammer it that much.

What is the easiest way to save an ArrayList in Android?

I'm building an app that has a favourites list, but when I exit the app, the favourites list is reset to nothing because the list is not being saved (since lists can't be saved in SharedPrefs). How can I save an ArrayList OR String[] in Android? If you recommend Serialization or a Local Database, could you please explain what these are and mean? I've heard the terms and followed tutorials but do not understand.
Maybe another approach to the same question is how would you normally build a favourites list?
There's a question that explains it in a very nice way:
Save ArrayList to SharedPreferences
From its answer (I've already tested it), after API 11 you can do something like this:
//Retrieve the values
Set<String> set = myScores.getStringSet("key", null);
//Set the values
Set<String> set = new HashSet<String>();
set.addAll(listOfExistingScores);
scoreEditor.putStringSet("key", set);
scoreEditor.commit();
I summarized his answer, but you should check the complete answer. It's really helpful!
Option1: easiest. Iterate over arraylist and save each element into sharedPreferences
option2: convert arraylist into a string. Then save into shared pref.
option3: save your data into a database. Google how to use sqllite with android
You can use Sugar ORM library for Android. It will create for you the database you need by simply making the object class of your ArrayList to extend SugarRecord.
For example, if your List type is ArrayList you have to make your Books class extend SugarRecord, and then in your Activity iterate in a loop through the items and set item.save() and it is saved to the database.
I have a sample project here.
If you have any question send me a PM.
Hope it helps!

How to keep track of information regarding fragments in Android

I have a fragment which is sort of like a test. The user can choose from a spinners menu if this test has passed, failed or undecided. Once the user leaves this fragment and then comes back to it later, I want the spinners menu to display what the user had previously selected.
Can anyone tell me how to keep track of this information? I am a beginner with Java and Android programming. Also, let me know if further explanation is required.
It probably depends on what scope you want to be able to refer to these tests in. For example, do you want these fragments to be emptied after the user closes the app, or not?
If it is just while in the app "session", you could just create an object in your fragment and override the onResume method to populate the spinners with the appropriate data.
If you want to save the info after the app is closed, there are a couple of options. For smaller sets of data you could use shared preferences
if you have an undetermined amount of "tests", I would advise saving whatever data you need to a file, and parsing it to fill the fields in the fragments
Take a look at this to get an idea of how to save data: http://developer.android.com/intl/es/training/basics/data-storage/files.html
I've done something similar to what your doing. I used shared preferences to save the string like so
Saving the string you got from the spinner in a fragment
SharedPreferences mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor mSharedPreferencesEditor = mSharedPreferences.edit();
mSharedPreferencesEditor.putString("my_unique_key", myString);
// commit changes
mSharedPreferencesEditor.apply();
Remember to always apply the changes after you made them and you can save as many strings as you want as long as they each have a unique key.
Then to retrieve the value just
SharedPreferences mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
String myStringValue = mSharedPreferences.getString("my_unique_key", null);
The second argument (null) will be returned if it could not find any data that had that unique key. (i.e if you haven't saved it yet)
You can also use another string instead of null like this
String myStringValue = mSharedPreferences.getString("my_unique_key", "could not find value");
or if you want to bundle a bunch of data together like say create an object to save a bunch of strings then save that object to a file I could show you that if you wanted to

Android: different ways of storing and reading variable values?

I have about 16 variables in which the values need to be saved for later recall / editing. I've tried SQLite Database, since I am a novice at Android, it is just too hard for me. I will have to come back to SQL later. Are there any other ways to store these values for later recall / editing? Thank you! Maybe link me to a tutorial if possible? :-)
You might try using SharedPreferences.
SharedPreferences is another choice. Here is a very simple example
how to use it.
Storing 16 variables using SharedPreferences will make your code looks long. I advise you to try harder with SQlite database.

Best way to save a little amount of data

I'm currently developing an Android application where OAuth will be in use. In order to use OAuth, I need to be able to save the consumer's private key to access the protected resources. My question is, where would I want to save this tiny piece of data? I know that for most Android applications, data would be stored in a SQLite database. But for only a little bit of information, a string containing random letters and numbers, would SQLite be the best way to go? Or would it just be better to write the data to a file and save it on the file system? I don't know what the best practice for this would be, so hopefully I'll be able to get some insight.
Thanks a bunch guys!
You have a lot of choices:
http://developer.android.com/guide/topics/data/data-storage.html
However, if you just want to save one String (the OAuth key), I would suggest shared preferences. Example:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("oauthKey", yourOAuthKey);
// Commit the edits!
editor.commit();
I would save it in a file on the internal storage or in shared preferences.
Never the less you should encrypt the key for security reasons! On a rooted oder developer device it is no problem to access any file on the system.
SharedPrefs is much easier to work with than an sqlite database - especially for something so simple as you describe.
I guess a SharedPreference would do just fine.

Categories