Show TOC

Caching the DataLocate this document in the navigation structure

(Optional, offline mode only) Caching is necessary for an application to work in offline mode. Use the Cache API to cache and persist data when the mobile device is out of the network range. The data is processed later when the device is within the range of the network.

Note Due to emulator limitations, you cannot determine the network connection state. See Emulator Limitations in Using the EmulatorInformation published on non-SAP site at the Android Developer Web site http://developer.android.com/index.htmlInformation published on non-SAP site.

The Cache API is divided into two parts, one that stores a copy of the entries you receive from the server, which is called a "server copy, " and one that stores locally modified entries, which is called a "local copy."

Prerequisites

Use the Caching interface, which is implemented by the Cache class, to create an object to work with.

Initializing a Cache

To initialize all the elements required for a cache to work, use the initializeCache method:

try{
      	ILogger logger = new Logger();
	ICache cache =new Cache(getApplicationContext(),logger);
	cache.initializeCache();
	 
   }
catch(CacheException e){
	Log.e("",e.getMessage();
}

You can cache data as either persistent, which means it is stored in a database, or as nonpersistent, which means it is stored in memory. By default, cache data is persistent.

If you do not want to store cache data in a database, use the following API:
cache.setIsPersistable(false);
Merging Data to a Cache

For all operations to work after a successful online GET request for a URL at the initial stagemergeEntries allows you to incrementally update the cache for server entries with the latest state of server objects. To enable the server cache to be in sync with the back-end service, ensure that every online HTTP GET operation on a URL is followed by a MergeEntries method. To avoid redundancies, optimize the GET operation with delta support.

try{
	 ILogger logger = new Logger();
Parser parser = new Parser(pref, logger);
	 ICache cache =new Cache(getApplicationContext(),logger);
cache. initializeCache();
IODataFeed feed = parser.parseODataFeed(entriesdoc, collectionID, schema);
	cache.MergeEntries(feed, EntryURL);parameters.
   }
catch(CacheException e){
	Log.e("",e.getMessage();
}

Note There is no time delay, when the parsed content is delivered for presentation, before it is merged to the cache, and when the merging operation is invoked on a thread, other than the current one.
Reading Entries from the Cache

You can read entries from the cache method either locally, or from the server.

  • Server entry All server entries are stored against a URL key, which is the endpoint from which entries are cached. Use the readEntriesServer method to read server entries.
  • Local entry Read the local entries based on the entity type (collection to which entry belongs to) and entry ID. Use the readEntriesLocal method to read local entries. Entity type and entry ID are optional parameters, but you must provide at least one parameter. Passing null to the entry ID parameter retrieves all the entries for a specified entity type. Passing null to as the entry type, along with passing a valid entry ID, retrieves the specified entry from cache.

    The ODataEntry class of the parser has two member properties. The getIsLocal() property checks if the particular entry is local, and getCachestate () checks if the local entry is created, updated, or deleted on the client. The cache states are represented by the cacheState{Updated,Deleted,Inserted} enum.

To show the latest version of data in your application, combine server and local entries:

/*Read entry from server.*/
try{
	 ILogger logger = new Logger();
	 ICache cache =new Cache(getApplicationContext(),logger);
cache.initializeCache();
	 List<IODataEntry> entries = cache.ReadEntriesServer(urlKey); // return all entries respective to the parameter.
   }
catch(CacheException e){
	Log.e("",e.getMessage();
}

/*Read entry from local*/
try{
	 ILogger logger = new Logger();
	 ICache cache =new Cache(getApplicationContext(),logger);
cache. initializeCache();
	 List<IODataEntry> entries = cache.ReadEntriesLocal(CollectionID,EntryID); // return all entries respective to  either of the 	parameters.
   }
catch(CacheException e){
	Log.e("",e.getMessage();
}
Managing Locally Modified Entries in Cache

You can manage entries in the local cache.

  • Adding an entry Use the addEntry() method to create a new entry in the local cache. With the Request library, perform an HTTP POST request to create an entry in the back end. After POST is successful, perform an HTTP GET request to fetch the latest server state, optimized with delta, and merge the result with the server cache on the device. Creating a local entry generates a temporary entry ID with which you can manage the cache entry.
    try{
          //Invoke the HTTP POST request
           ODataEntry entry = new ODataEntry();
           entry.putPropertyValue("<property_name>", "<property_value>");
           String postbody = Parser.buildODataEntryRequestBody(entry, "<collection_ID>", schema, IParser.FORMAT_XML);
    
    	   ILogger logger = new Logger();
    	   ICache cache =new Cache(getApplicationContext(),logger);
    	   String generated_id =cache.addEntry(entry);
    	 //Invoke the HTTP POST request
           BaseRequest post = new BaseRequest();
           post.setRequestMethod(BaseRequest.REQUEST_METHOD_POST);            
           post.setData(postbody.getBytes());
           reqMan.makeRequest(post);
       }
    catch(CacheException e){
    	Log.e("",e.getMessage();
    }
    
  • Updating an Entry to Cache When you make changes to data that is stored locally on your device in offline mode, the data must be cached and persisted locally to be updated in the backend when connectivity returns. The update entry procedure ensures the OData entries are cached to build an application that works seamlessly both offline and online. Use the updateEntry method to create a local copy of the updated entry in cache. When connected, perform an update on the back end using an HTTP PUT request. After the update is successful, perform an HTTP GET request to fetch the latest server state optimized with delta, and merge the result with the server cache on the device. The updateEntry method does not generate any temporary ID, as the entry is already associated with the ID generated by the back end.
    try{
    	 ILogger logger = new Logger();
    	 ICache cache =new Cache(getApplicationContext(),logger);
    cache. initializeCache();
             	cache.updateEntry(entry);
       }
    catch(CacheException e){
    	Log.e("",e.getMessage();
    }
    
  • Deleting an Entry from Cache Use the deleteEntry method to delete a new entry with its ID from the local cache. When connected, perform an HTTP DELETE request on the backend to deleted the entry in back end. Post a successful delete on the backend, perform an HTTP GET request to fetch the latest server state optimized with delta, and merge the result with server cache on the device. The SDK reads the entry from the server cache, based on the entry ID, and updates the entry in the local cache by marking it as a local copy to be deleted. The deleteEntry method does not generate any temporary ID, as the entry is already associated with the ID generated by the back end.

    The delete tombstones for delta query support are not available on OData JSON format.

    try{
    	 ILogger logger = new Logger();
    	 ICache cache =new Cache(getApplicationContext(),logger);
                cache. initializeCache();
    	  cache.deleteEntry(EntryID);
    
       }
    catch(CacheException e){
    	Log.e("",e.getMessage();
    }
    
  • Correlating Requests with Local Cache Entries Each operation, such as adding, updating, and deleting local cache entries is associated with a unique ID. These operations are also associated with requests. For example, an add operation corresponds to a POST request. The Request object interface provides a way to to tag each request with its respective entry ID.
    Each request to a single endpoint is associated with single cache entry ID.
  • Clearing Specific Data To clear locally created entries when all cache instances are updated with the server version of the entry on which modifications have been made, use the clearLocalEntryForEntryId method.
    Note Since the local cache is specific to the entry ID, the changes made to an entry from one of the cache instances (for example query parameter, URL?$top=10) should be reflected on all cache instances in which the entry is present (for example, URL?$top=20 ). Do not delete the local entry until you have refreshed all caches that are relevant for this entry.
    try{
    	 ILogger logger = new Logger();
    	 ICache cache =new Cache(getApplicationContext(),logger);
    cache. initializeCache();
    	 cache.clearLocalEntry(<EntryID>);
    
       }
    catch(CacheException e){
    	Log.e("",e.getMessage();
    
Storing a Document in Cache
To cache the service and metadata document (schema) for a particular service URL, use the storeDocument method. You can also define your own enum type and store the data for that enum type. Store the service document only after the metadata document is parsed.
//Service document
try{
	 ILogger logger = new Logger();
	 ICache cache =new Cache(getApplicationContext(),logger);
cache. initializeCache();
	 cache.storeDocument(serviceDocumentObject, DocumentType.ServiceDocument, serviceDocUrl);
   }
catch(CacheException e){
	Log.e("",e.getMessage();
}

//MetaData Document
try{
	 ILogger logger = new Logger();
	 ICache cache =new Cache(getApplicationContext(),logger);
	cache.initializeCache();
	cache.storeDocument(serviceDocumentObject, DocumentType.MetaDocument, serviceDocUrl);
}
catch(CacheException e){
	Log.e("",e.getMessage();
}
Reading Document from Cache

To read the service and metadata documents from cache, use the readDocumentForUrlKey method. This method returns the stored document in the cache. The application should pass the document type and the URL for which the document is relevant.

try{
	 ILogger logger = new Logger();
	 ICache cache =new Cache(getApplicationContext(),logger);
     cache.initializeCache();
	 IODataServiceDocument serviceDocumentObject = (IODataServiceDocument )cache.readDocument(DocumentType.ServiceDocument, serviceDocUrl);
	 IODataSchema metadata = (IODataSchema)cache.readDocument(DocumentType.MetaDocument, serviceDocUrl);
   }
catch(CacheException e){
	Log.e("",e.getMessage();
}
Clearing the Cache

Use the clearCache method to clear the cache and persistence of all the entries based on the URL key. This method also deletes the delta token of any document that is stored against this URL. Use this method only when the application does not support delta queries.

try{
	 ILogger logger = new Logger();
	 ICache cache =new Cache(getApplicationContext(),logger);
cache.initializeCache();
	 cache.clearCache(URLKey);

   }
catch(CacheException e){
	Log.e("",e.getMessage();
}
Using Delta Link

The delta link retrieves the delta changes for a URL, since the last time the URL was called.

Note You must pass the complete request URL as urlKey. For example, cache().mergeEntries(list, aRequest.getRequestUrl()).

The default option for a cache is to get the delta link if the OData entry supports it. Once the mergeEntries API is invoked to save server entries into cache, the next GET fired by the application is for the delta link for the OData entry. Only delta changes are available, as the response and the application developer can call mergeEntries to merge the entries in the cache.

The application developer can disable default delta link handling by calling

requestObject.disableDeltaHandling(true);