File or Database? - Best Practice to save Objects on Android-Device

喜欢而已 提交于 2019-12-09 15:41:58

问题


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?


回答1:


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.




回答2:


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.




回答3:


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?




回答4:


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.



来源:https://stackoverflow.com/questions/18016778/file-or-database-best-practice-to-save-objects-on-android-device

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!