Reputation: 737
I'm building an android application in java where I define some Objects like "user" or "playlist" etc..
How to save these self-defined objects on the device for later access?
Gson gson = new Gson();
String json = gson.toJson(user);
I can parse the objects via GSON to a JSONObject or a JSONArray. Now I have two options to save the strings: In a Database or a File. I know how to use the android database-classes and the filewriter/reader classes, but what is the best practice with regards to performance, accessibility and especially to simplicity?
Upvotes: 9
Views: 10679
Reputation: 6451
It really depends on your use case.
If your application data doesn't change a lot (think a conference app that is used once or twice a year), then you can use a ContentProvider + CursorAdapters which will make your life easier.
If your application data changes a lot (think Gmail, where as much as hundreds of email can pop-up every day, or a news feed, or a social networking app like Google+), then a database could probably make your life worse. You should use in this case a 3rd party caching system, like Google Volley or RoboSpice, etc. which handles all the caching of JSON objects for you and all the concurrency problems that appear, etc.
Upvotes: 5
Reputation: 7663
Use a database
. Your JSON can easily be parsed and read in to the database. Plus you can use SQL
queries to find and manipulate the data anyway you need in the future. A flat file will not allow you the same flexibility. Files can be useful for other applications but for JSON, broken into objects, representing things - a database makes much more sense.
Upvotes: 1
Reputation: 17171
The database scales well, the database engine solves the problem of memory management, the database has good performance (when used properly), the database engine allows you to run complex queries without writing a lot of Java code, the database engine allows you to insert or delete rows without writing an entire file, the database is natively supported in Android's widgets. Remember that you're limited how much memory your app can use, so if your JSON files get very big, you won't be able to load them entirely into memory.
Upvotes: 5
Reputation: 2483
The SQLite db built in to Android would be a good solution for caching large amounts of information. For instance, if you are constantly retrieving data from the cloud and then planning on storing it, you should use a db. Dbs are built for handling large amounts of data because they include indexing capabilities.
An example of caching JSON data with SQLite db can be found here: Caching downloaded JSON data to SQLite database - is it a good idea?
Upvotes: 1