Data Caching and Synchronization

Duration

25 minutes

Tip: If you are doing this exercise live in a session, make sure to make good use of the instructor, they are online to answer any questions you have!

Goals

The goal of this exercise is to modify a movie search application that connects to an external server to work offline by caching search results locally.

iTunes Search API Service example using offline caching

Development environment notes

In order to test the application you will need either a real device or a simulator that allows turning the device network on and off. For Android you can use either a simulator or a physical device. For iOS it is preferred to use a real device. Refer to the slides demonstrating how to simulate network failures on the simulators or emulators.

Required assets

The provided Exercise 1 folder contains both a starter project you will be modifying as well as a completed solution you can use to check your work.

Exercise overview

We have an existing application that will connect to the network and download results from a server. You will modify the application to make it work while offline by checking for connectivity to the network and providing the ability to load data locally when no network connection is available.

Our basic steps will be:

  1. Check for network connectivity
  2. Store the data from the remote server to the local cache
  3. When the network is unavailable, load the cached results

Steps

Below are the step-by-step instructions to implement the exercise.

Check for network connectivity

In this section we are going to check for network connectivity when calling the network service and alter the application so it can use an offline cache when no connection is available.

  1. Open the solution MovieSearch.sln in the Exercise 1/Start folder. This Xamarin.Forms application solution has four projects in it:
  2. Project Description
    MovieSearch The PCL shared code project which contains the majority of the UI and business logic.
    MovieSearch.Droid The Android-specific platform project.
    MovieSearch.iOS The iOS-specific platform project.
    MovieSearch.UWP The Universal Windows Platform head project.

  3. Add the Connectivity Plugin for Xamarin to each of the projects using Nuget. In Visual Studio for Mac, you will need to do this individually for each project by right clicking on the Packages folder and selecting "Add Packages". Visual Studio for Windows allows you to manage all the projects at once by right-clicking on the root solution node and selecting "Manage Nuget Packages".
  4. Open the MovieRestService.cs source file in the RestService folder in the MovieSearch project and locate the GetMoviesForSearchAsync method. Add a call to the top of this method to CrossConnectivity.Current.IsRemoteReachable to determine if you can connect to the server; use the HostName value as the target. If the method indicates that you cannot connect to the server, throw an Exception.
    • Hint: the IsRemoteReachable method returns a Task<bool> so make sure to await it to get the result!

Show Code

  1. Open IncrementalSearchPage.cs in the Utility folder.

    This file is a base class used to provide all the incremental loading logic for some type (T). It provides the UI for a search bar, offline notification and loading activity indicator. You won't need to make any changes to this file in the lab, but it's a nice example of integrating some of these features into your app.

  2. Locate the DoLoadAsync method. Examine the loading mechanism that is implemented.
    • It first attempts to load the data from the network and if the network fails then it will fall back to loading content from the cache.
    • The data loading methods are virtual so our MovieSearchPage.cs file can override them and provide the specific behavior.
    • All attempts to load the content (online and offline) are wrapped in a try / catch in the event of a network fail at anytime. In this way we can use traditional Exception management to handle failures to the server for any reason.

Store the data from the remote server to the local cache

In this section we are going to alter our network calls so that when we receive data from the remote service it is saved to a local cache.

  1. Open the MovieSearchPage.cs file.
  2. After the data has loaded in the LoadPageFromNetworkAsync method, store the data to the local database using the DataManager.StoreMoviesAsync method just before it is returned from the method.

Show Code

  1. In the Data folder, open the DataManager.cs file and navigate to the StoreMoviesAsync method. This method currently has no implementation, but it needs to store all the passed records (the movies parameter) into the SQLite database.
  2. Implement the method, here are some hints:
    • The primary key according to the iTunes services is stored in the ID column.
    • Update the movies that you have retrieved from the service. On the SqliteAsyncConnection you can use the InsertOrReplaceAsync method to insert or update entries in the Movies table.
    If you aren't familiar with SQLite, use the code below to fill in the implementation, and then make sure to take the XAM160 class from Xamarin University!

Show Code

When the network is unavailable, load the cached results

In this section we are going to determine if the network is unavailable, and if so, load the results from the cache and notify the user.

  1. Open the MovieSearchPage.cs and navigate to the LoadDataFromCacheAsync method. This method currently returns null.
  2. Implement the method so that it returns the records using MovieSearch.DataManager.GetMoviesAsync method.

Show Code

  1. Run the application on a local device or simulator connected to the network and perform some data queries in order to populate your cache.
  2. On your device or simulator, turn off the network access and attempt to perform the same search. You should be able to see the data populate from the cache.
    Note, the Google emulators will not lose connection to the IDE when airplane mode is enabled. It is recommended to launch the application from the emulator manually and then disable/enable airplane mode to test.

Summary

In this exercise you enabled caching of data retrieved from a webservice and presented the cached data to the user when the device is not able to reach the webservice.

Go Back