I would like to know what would be the best option to store a custom Java object that I have in my application. I've read about serialization but it seems to be quite slow.
What is the best option?
To save a file to the internal storage, you must first obtain it from the internal directory. You can do this by calling the getFilesDir() or getCacheDir() methods. The getFilesDir() method returns the absolute path to the directory where files are created on the filesystem.
Saving object in java can be accomplished in a number of ways, the most prominent of which is to serialize the object - saving it to a file and reading the object using an ObjectOutputStream and ObjectInputStream, respectively. Serialization is a fantastic advantage to using java. However, it has its drawbacks.
If you're not storing an over abundance of data you can use Gson to convert a Java object to a Json string and store the string in your app preferences. Gson has a toJson(obj) method and visa-vis.
Getting data out of app preferences and into an object:
String json = appSharedPrefs.getString("someName","");
return gson.fromJson(json, YourModel.class);
To get data from your object into app preferences:
String json = gson.toJson(obj);
Then prefsEditor.putString("someName", json).apply()
.
You should read:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With