For an application which will allow members of my organisation to see data on their mobile device i need to store pre-formatted data on the device so they can see it offline as well. How they get the data is trough a JSON request-response.
The response is formatted as follows (anonymised ofc):
[{
"firstname":"John",
"lastname":"Smith",
"group":"1",
"age":11,
"installed":"Ja",
"medical":"Is aan zijn linker zijde verlamd geweest.",
"notes":"Heimee. \r\nBeschermend opgevoed. \r\nTerug getrokken persoonlijkheid.",
"Insignes":["test", "Test2"],
"Parents":[]
},
{
"firstname":"Emely",
"lastname":"Watson",
"group":"33",
"age":14,
"installed":"Ja",
"medical":"",
"notes":"Test",
"Insignes":["Veilig & Gezond I","CWO II","CWO III","Kampeertechnieken & Pionieren"],
"Parents":[
{
"name":"ouder ouder",
"address":"op | 0000AA Amsterdam",
"phone1":"",
"phone2":"0612345678",
"mail":"example#google.com"
}]
}]
I have read a couple of discussion on how to best store this:
Is it ok to save a JSON array in SharedPreferences?
How to save JSON Array in SharedPreferences?
Android: what is the best way to store JSON data offline for the app in android?
Android - how to add JSON object to sharedPreferences?
What is the advantage of Using SQLite rather than File?
From reading these I have gathered that SharedPreference files are "faster" than sqlite but are prone to corruption. SQLite is a database and since the data comes from one I am inclined to use that at the cost of processing speed.
Now I only need to store and then read the data, it wont be mutated unless there is an update on the "main server" in which case I will probably wipe the local data and repopulate it. In these threads i have read that storing JSON in sharedpreference is easy but difficult to read.
But after reading these (and more) discussions I am no closer to knowing/deciding what the best way to store my json is.
Any advice is greatly appreciated!
You can try the ORMs like Realm or sugarORM and store the json has object in the database. They also provide the Cipher options by which you can encrypt the data too, Which would be more flexible.
http://www.androidauthority.com/use-android-keystore-store-passwords-sensitive-information-623779/
http://www.androidhive.info/2016/05/android-working-with-realm-database-replacing-sqlite-core-data/
If you don't need to use any ORM by third parties then you can directly encrypt the JSON string with the android keystore keys and then can store the encrypted string in the normal sqlite.
This is opinion based answer. Android no I wouldn't store JSON in a DB or preferences. Store the json in a file. A file can be accessed as stream the same way you stream access json. Virtually no upper limit on size in a file. I might store a link to the json file in a DB or preferences. Depending on application I might just extract json into abstract elements and store in DB for ordering selection.
The data you have provided depending on sensitivity I would extract and insert into the contacts database for the device.
The best option is to go with a database approach, for one it sounds your dataset might be large are rather expected to be large. Database persist large sets of information, however I do not recommend using SQLITE , for it is sql based, no ORM and the operations can get tedious and time consuming and mainly it is slow(debatable). Rather use the hottest and latest no-sql database for android and ios, which Realm, realm is super fast, it is based on java annotations and ORM(like hibernate). To work with json in android I recommend familiarizing yourself with GSON, A Java serialization/deserialization library that can convert Java Objects into JSON and back.
Shared Preferenences are really convenient to store small key value pairs, If you have a relatively small collection of key-values that you'd like to save, you should use the SharedPreferences APIs. A SharedPreferences object points to a file containing key-value pairs and provides simple methods to read and write them. You would of to still work with gson here, I never heard of a shared preference getting corrupted, what I do know is that they are fragile,and live with the existence of your app installation.
Conclusion: If your dataset is large use a database approach to persist large dataset, maintenance and modifications are more fluent here, however if you know that whatever you are storing is relatively small, use a shared pref, and to manipulate json constructs in android to and fro use the google gson library.
SharedPreferences :
If you have small amount of data in Json then you have to store it in SharedPreferences.
You can easily store Json to SharedPreferences using Gson. Just using this :
Convert Json to String :
Gson gson = new Gson();
String jsonString = gson.toJson(jsonData);
Convert String to Json :
gson.fromJson(jsonString, TypeToConvert);
Sqlite Database :
If you have large amount of data in Json then just go with Sqlite.
I'm working on Android app with Google App Engine JAVA backend.
I've got Entity object from app engine backend, and I need to pass it from one Activity to another in Android app. Puting it into bundle as serializable extra throws exception, most probably because my Entity class doesn't implements Serializable (and I guess it can't implement it).
What would be the proper way to serializing entities objects at client side, for bundle packing purposes?
You better use GSON to do this.
Gson is a Java library that can be used to
1. Convert Java Objects into their JSON representation.
2. And also Convert a JSON string to an equivalent Java object.
Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.
I found that Gson isn't all that reliable and it takes a lot to write the Adapter. I went to EventBus for help and it works great! :)
The application I am working on is primarily based on manipulating JSON data obtained from the server. Traditional JSON parser extracts values, sets required POJOs and passes on to UI handler to render. This part is working well for now.
I have heard of GSON library and run through its implementation steps. As per my understanding, it (GSON usage) requires the following.
JSON data in proper syntax.
Model class objects matching JSON response.
GSON injector or code snippet to fetch JSON from the server and feeds to GSON.
The above approach sounds rather like object mapping. However, I am unaware about how efficient is GSON compared to old-fashioned JSON parsing; particularly with complex JSONs. And its implications on memory usage?
What do you think?
GSON has been successfully used in several android apps that are in Google Play today. The benefit you get with GSON is that object mapping can save the time spent writing code. As for the implications on memory usage, you can use the fromJson() method call that takes a streaming JSONReader to minimize the String data that is kept in memory, failing which you can try to parse the json data using a JSONReader yourself.
the GSON's goals is well described on official page:
Gson Goals:
Provide simple toJson() and fromJson() methods to convert Java objects to JSON and vice-versa
Allow pre-existing unmodifiable objects to be converted to and from JSON
Extensive support of Java Generics
Allow custom representations for objects
Support arbitrarily complex objects (with deep inheritance hierarchies and extensive use of generic types)
https://code.google.com/p/google-gson/
I'm very new to Android and I'm currently working on Android app that will parse JSON from a Restful API and display some of the data in a list view. I've looked into using GSON for parsing as the JSON was quite complex. Now my main problem is figuring out how to store the data somewhere so the app doesn't need to reload itself every time the activity is clicked on. I've looked at few questions here but they all seem to point to JSON only not GSON. Could anyone recommend an efficient way of doing this?
Thanks
if you want to store the data permanent it's the best way to insert your deserialized objects into a sqlite database or store them local to the disk as a file.
if your intention is to load the data for each startup, it's easier. just put your object into a public static object. so you can check if the object is not null or not. if it's null you have to load the data.
another opportunity is using the SharedPreferences.
I am currently working on TFL based projects. And i want to parse the json file which is available in this link : http://countdown.api.tfl.gov.uk/interfaces/ura/instant_V1
So please help me out
This API is not standard JSON as written in the TFL API documentation. It us actually best parsed as CSV but watch out because I have found out that some responses are inconsistent where the first line might have 6 strings while the second might have 5 with the missing field not identified as an empty string but simply omitted. This way parsing with a CSV parser will lead to errors since you might never know what is omitted.
I have also searched for the solution and the best I could find was another API that gives standard JSON but only returns bus stop countdown via a stopCode request.
Use This Link To Access It.
http://countdown.tfl.gov.uk/stopBoard/75288
Im suprised as to why TFL uses this api for their own apps but not implement the public api to return good JSon like this one.
This API is not standard JSON as written in the TFL API documentation.so after get the content you may change that format. Use this link http://jsonlint.com/ it will validate your json format. so you can easily understand json format error
After get the content do this
JSONArray jArray = new JSONArray("["+ result.replaceAll("]", "],").toString() + "]")
now you get proper json array skip jArray 0th position this is - URA Version array.
It is not a single full JSON object, as per the TFL documentation. You treat each line as a separate JSON object. This way if/when you move to the streaming mode, you can continue to receive objects and interpreting them as they get streamed to you. Also you use the first element in the JSON array to determine how to process that particular line, or in some cases if you need to refresh the base data.