Android: how sqlite database could be used to store the user data when internet is not available and then synchronise the stored data automatically with server when device is connected to internet (i want the scenario how it works) my data will contain strings, as well as images, but i will store image path instead of images in sqlite database.
if anybody can explain me with simple example code then it will be grateful am just a beginner.
create a SQLite database in your application in order to store all the information locally. Here you can get a detailed tutorial on creating and maintaining a SQLite database for your application. SQLite Tutorial
Inside your SQLite table's you can make a filed like isSynced and toggle it's bit from 0 to 1 depending upon that the record is updated on the server or not.
Create a service that you can run on the start of your application but make a check to run that service only if it is not running. That service will scan all the tables of the database at every 2 minutes whose isSynced bit is 0 i.e. those records that need's to be updated to the server, make sure to check the internet connection before scanning the database so that the it can send the records at the same time. At this point you will get a list of the records that need's to be updated on the server. Now hit your service in the loop to send the records to the server and as soon as a record is successfully saved on the server make sure to update it's isSynced bit to 1. Here you can read a detailed tutorial on Service in Android
In-order to check the internet connection you can try the following code:
public static boolean isConnected(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED)
return true;
}
}
}
return false;
}
You also need to add the following permissions in your Manifest file:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
You can also check this tutorial that will help you in communicating with the web services
Hope this will help so in achieving you Goal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With