Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: How to synchronize the sqlite data with server [duplicate]

Tags:

android

sqlite

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.

like image 974
Jolson Da Costa Avatar asked Dec 20 '22 12:12

Jolson Da Costa


1 Answers

  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:

    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.

like image 107
Abhishek Dhiman Avatar answered Dec 22 '22 03:12

Abhishek Dhiman