Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store objects in Android

Tags:

android

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?

like image 673
feeder1803 Avatar asked Mar 16 '11 12:03

feeder1803


People also ask

How to store data in Android?

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.

How do you store objects in Java?

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.


2 Answers

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().

like image 120
Bill Mote Avatar answered Oct 12 '22 00:10

Bill Mote


You should read:

  1. Best method for saving data - preferences, sqlite, serializable or other?
  2. Data Storage
like image 41
Macarse Avatar answered Oct 11 '22 22:10

Macarse