Hi I want to know what is the best way to save data coming from external link in json fromat
in the SQL lite database
and if there is no internet connection … the application will retrieve data from SQL database
Hi @aboulfotouh,
I did this for caching and works fine.
Use e.g. https://ionicframework.com/docs/native/sqlite/ to add sql support and store the json data you retreived via the http request in your local database together with an identifier (in my case the url params I use for the request).
In second step, add https://ionicframework.com/docs/native/network/ to check what kind of connection (none at all, 3G, …) you have and depending on the answer retreive the data from your database with the url params in a query to select the right local data set or get it via http.
Very minimalistic example:
if(!this.checkNetwork()){
this.getCacheData(params)
}else{
this.loadData(params);
}
checkNetwork(){
//Uses ionic native network to check if there is a connection or not and returns true or false
}
getCacheData(params) {
//Perform the acual database query with your params
//Don't forget to sanitize any input before doing the acual query!!!
//If there is no data in storage matching your params, trigger an error message your the user telling him to reload or wait a little
}
loadData(params){
//Retreive your data via http request from your server.
//In case the server is not available at that moment, you could implement a fallback and requesting the cached data from local storage instead.
//In case of a successfull request, store the response in your local database for future usage
}
triggerError(){
//Show error message if no cached data is available or data could not be loaded
}
The above example is quite simple but it should explain the general concept I think.
Think about whether you really need to be interacting with SQLite. Ionic Storage is much simpler to deal with and works in browsers as well, making development much easier.
thank you for the clear example
but it’s better to save the data in SQLite or caching it ?
As rapropos said, you could also use Ionic storage. These are the only two ways i’m aware of at the moment to effectively store your data on a device.
And regarding “it’s better to save the data in SQLite or caching it?”: Storing data localy is caching in some ways. If you make yourself independent from an internet connection with storing a server response for future use, you do cache it.
I usually use SQLite for caching content as I need it for other stuff too, but the ionic storage solution should be enough in your case i think
Kindly fill in sample codes for each of the functions for better understanding. Thanks.