Search code examples
androidxmldatabaseupdate-site

How to get data from server and update the database with it?


I am implementing an android application and i can't figure out how to solve this problem : When user clicks to the update button , i want to connect to the my server and check if there is any update on the data , if there is , i want to get data from server and update the database.Should i use xml structure to check and get updates from server or is there any smarter ways to achieve this ?


Solution

  • Yes, there's a smarter way to do so, it will require some work on both server and client side though. This is how it works: all data should be available to download in JSON or XML format (I'd rather prefer JSON). So, you will have something like this in the server: http://example.com/resource.json. In order to know if there's a new version of the data, what you can do is adding a header version to the HTTP response (that way you don't have to download and parse the whole resource in order to know if there's a new version).

    In order for you to check those headers, you will have something like this:

    URLConnection urlConnection = null;
    try {
        urlConnection = url.openConnection();
        urlConnection.connect();
    
        String currentVersionHeader = urlConnection.getHeaderField("your-version-header");
        if( currentVersionHeader == null ) {
            currentVersionHeader = "-1";
        }
    
        int version = Long.parseLong(currentVersionHeader);
    
        // then you compare with the old version
        if( oldVersion < version ){
            // download the data
        }
    } catch (Exception e) {}
    

    Downloading and parsing a JSON resource is something that has been already treated and you will find a bunch of tutorials and references on Google and here.

    You are not providing details of the server side (is PHP? Java? .NET?), so I also won't give you details of how to implement/add a version header. I'm just explained you what's one the best way to do this kind of things based on my own experience.