Skip to content Skip to sidebar Skip to footer

Android: How To Synchronize The Sqlite Data With Server

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 conne

Solution 1:

  1. 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

  2. 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.

  3. 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

  4. In-order to check the internet connection you can try the following code:

    publicstaticbooleanisConnected(Context context) {
        ConnectivityManagerconnectivity= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (inti=0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED)
                        returntrue;
                }
            }
        }
        returnfalse;
    }
    

You also need to add the following permissions in your Manifest file:

<uses-permissionandroid:name="android.permission.INTERNET" /><uses-permissionandroid: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.

Post a Comment for "Android: How To Synchronize The Sqlite Data With Server"