Sync data between Android App and webserver

208,392

Solution 1

I'll try to answer all your questions by addressing the larger question: How can I sync data between a webserver and an android app?


Syncing data between your webserver and an android app requires a couple of different components on your android device.

Persistent Storage:

This is how your phone actually stores the data it receives from the webserver. One possible method for accomplishing this is writing your own custom ContentProvider backed by a Sqlite database. A decent tutorial for a content provider can be found here: http://thinkandroid.wordpress.com/2010/01/13/writing-your-own-contentprovider/

A ContentProvider defines a consistent interface to interact with your stored data. It could also allow other applications to interact with your data if you wanted. Behind your ContentProvider could be a Sqlite database, a Cache, or any arbitrary storage mechanism.

While I would certainly recommend using a ContentProvider with a Sqlite database you could use any java based storage mechanism you wanted.

Data Interchange Format:

This is the format you use to send the data between your webserver and your android app. The two most popular formats these days are XML and JSON. When choosing your format, you should think about what sort of serialization libraries are available. I know off-hand that there's a fantastic library for json serialization called gson: https://github.com/google/gson, although I'm sure similar libraries exist for XML.

Synchronization Service

You'll want some sort of asynchronous task which can get new data from your server and refresh the mobile content to reflect the content of the server. You'll also want to notify the server whenever you make local changes to content and want to reflect those changes. Android provides the SyncAdapter pattern as a way to easily solve this pattern. You'll need to register user accounts, and then Android will perform lots of magic for you, and allow you to automatically sync. Here's a good tutorial: http://www.c99.org/2010/01/23/writing-an-android-sync-provider-part-1/


As for how you identify if the records are the same, typically you'll create items with a unique id which you store both on the android device and the server. You can use that to make sure you're referring to the same reference. Furthermore, you can store column attributes like "updated_at" to make sure that you're always getting the freshest data, or you don't accidentally write over newly written data.

Solution 2

If we think about today, accepted answer is too old. As we know that we have many new libraries which can help you to make this types of application.

You should learn following topics that will helps you surely:

  • SyncAdapter: The sync adapter component in your app encapsulates the code for the tasks that transfer data between the device and a server. Based on the scheduling and triggers you provide in your app, the sync adapter framework runs the code in the sync adapter component.

  • Realm: Realm is a mobile database: a replacement for SQLite & Core Data.

  • Retrofit Type-safe HTTP client for Android and Java by Square, Inc. Must Learn a-smart-way-to-use-retrofit

And your sync logic for database like: How to sync SQLite database on Android phone with MySQL database on server?

Best Luck to all new learner. :)

Solution 3

If you write this yourself these are some of the points to keep in mind

Proper authentication between the device and the Sync Server

A sync protocol between the device and the server. It will usually go in 3 phases, authentication, data exchange, status exchange (which operations worked and which failed)

Pick your payload format. I suggest SyncML based XML mixed with JSON based format to represent the actual data. So SyncML for the protocol, and JSON for the actual data being exchanged. Using JSON Array while manipulating the data is always preferred as it is easy to access data using JSON Array.

Keeping track of data changes on both client and server. You can maintain a changelog of ids that change and pick them up during a sync session. Also, clear the changelog as the objects are successfully synchronized. You can also use a boolean variable to confirm the synchronization status, i.e. last time of sync. It will be helpful for end users to identify the time when last sync is done.

Need to have a way to communicate from the server to the device to start a sync session as data changes on the server. You can use C2DM or write your own persistent tcp based communication. The tcp approach is a lot seamless

A way to replicate data changes across multiple devices

And last but not the least, a way to detect and handle conflicts

Hope this helps as a good starting point.

Solution 4

@Grantismo provides a great explanation on the overall. If you wish to know who people are actually doing this things i suggest you to take a look at how google did for the Google IO App of 2014 (it's always worth taking a deep look at the source code of these apps that they release. There's a lot to learn from there).

Here's a blog post about it: http://android-developers.blogspot.com.br/2014/09/conference-data-sync-gcm-google-io.html

Essentially, on the application side: GCM for signalling, Sync Adapter for data fetching and talking properly with Content Provider that will make things persistent (yeah, it isolates the DB from direct access from other parts of the app).

Also, if you wish to take a look at the 2015's code: https://github.com/google/iosched

Solution 5

For example, you want to sync table todoTable from MySql to Sqlite

First, create one column name version (type INT) in todoTable for both Sqlite and MySql enter image description here

Second, create a table name database_version with one column name currentVersion(INT)
enter image description here

In MySql, when you add a new item to todoTable or update item, you must upgrade the version of this item by +1 and also upgrade the currentVersion enter image description here

In Android, when you want to sync (by manual press sync button or a service run with period time):

You will send the request with the Sqlite currentVersion (currently it is 1) to server.
Then in server, you find what item in MySql have version value greater than Sqlite currentVersion(1) then response to Android (in this example the item 3 with version 2 will response to Android)

In SQLite, you will add or update new item to todoTable and upgrade the currentVersion

Share:
208,392

Related videos on Youtube

Omid Nazifi
Author by

Omid Nazifi

I am a curious person who want to learn everything. Working as a team player and focusing on Java issues are my interests.

Updated on July 16, 2022

Comments

  • Omid Nazifi
    Omid Nazifi almost 2 years

    I want to sync data (such as db record, media) between an Android App and a Server. If you've seen Evernote or similar Applications, you certainly understand what I mean.

    I have some question (imagine we want to sync DB records):

    1. Every user has a part of server space for himself (such as Evernote or Dropbox). Maybe the user creates new records by cellphone and creates new records in server. How can I match these records together? If there are records with same ID What algorithms do you suggest me?

    2. Except JSON, Are there any way for send data between cellphone device and server?

    3. If SyncAdapter and ContentProvider can solve my problems, please explain exactly for me. (If you could offer some samples or tutorials to me OR Any advice or keywords to help broaden/guide my search would be appreciated as well).

    • hovanessyan
      hovanessyan almost 12 years
      First you need to figure out(decide on) your communication protocol with the server - hence - what data you can transfer and how.
    • Omid Nazifi
      Omid Nazifi almost 12 years
      That is Important for me, transfer SQLlite data. but I would know how transfer other data. I don't understand your mean about protocol. please more explain.
    • hovanessyan
      hovanessyan almost 12 years
    • saimadan
      saimadan over 8 years
      try konysync, a product of konylabs which provides end-to-end solutions across various platforms(android,windows,ios) , webservers , data providers(salesforce,sap providers),databases(sqlserver,mysql...)
  • Omid Nazifi
    Omid Nazifi almost 12 years
    How to check data updated in local App and server? and How to merge together? It's not good that I send all of record by JSON or anythings to application for merge them. what do you think?
  • Evan R.
    Evan R. over 11 years
    you could use a flag, such as "on server" with a int/bool 1/0 for yes or no. when a record/file/block of data gets sent, check for success at server, and flip the bit to yes. then if you're using something like SQLite, you can do a "SELECT * FROM my_table WHERE sent = 0" type thing to send any new records
  • Pratik Butani
    Pratik Butani over 9 years
    What about large amount of data? how can i sync?
  • MRodrigues
    MRodrigues almost 9 years
    Very well explained I just have a note... SyncAdapter -> "perform lots of magic". I hope you are referring it as black magic...it's totally evil.
  • praxmon
    praxmon over 8 years
    What are the free plans that the offer?
  • Milad Metias
    Milad Metias over 8 years
    @MRodrigues : SyncAdapter could be black magic for the developer but it still do magic for stability and functionality , it is much more better than other libs
  • Richeek
    Richeek over 8 years
    The source code for Google IO app is pretty useful IMO!
  • Chintan Rathod
    Chintan Rathod about 8 years
    http://parse.com/ is shut down.
  • geniushkg
    geniushkg about 8 years
    you can still use parse.com functionality , but on your own server , they have opensourced
  • jublikon
    jublikon almost 8 years
    What does the webservice itself require to sync it with an android device? Is it possible with Spring?
  • Ahesanali Suthar
    Ahesanali Suthar over 7 years
    Your idea is brilliant but still can't understand table design properly. Along with rest services and proper synchronization service it works
  • Greg Holst
    Greg Holst over 5 years
    Link to a-smart-way-to-use-retrofit is dead
  • Pratik Butani
    Pratik Butani over 5 years
    @GregHolst updated.
  • bobpaul
    bobpaul about 5 years
    Still down. Or requires login? Archive.org has it: web.archive.org/web/20160316222227/https://futurestud.io/blo‌​g/…