Android

Use Contentstack to power content for your Android projects

Create Android-based applications and use the Android SDK to fetch and deliver content from Contentstack. The SDK uses Content Delivery APIs.

Getting Started

This guide will help you get started with our Android SDK to build apps powered by Contentstack.

Prerequisites

To get started with Android SDK, you will need one of the following: Android Studio or Eclipse.

SDK Installation and Setup

To add the Contentstack Android SDK to your existing project, perform the steps given below:

  1. Download the Android SDK and extract the ZIP file to your local disk.
  2. Add references/dependencies using Eclipse/Android Studio:
  3. Android Studio:

    1. Copy the 'Contentstack-x.x.x.jar' file into your project's libs folder.
    2. Add the dependency code into your 'build.gradle' file.
    3. compile fileTree(dir: 'libs', include: ['*.jar'])

    Eclipse:

    1. Copy the 'Contentstack-x.x.x-javadoc' folder and the 'Contentstack-x.x.x.jar' and 'Contentstack-x.x.x.jar.properties' files into your project's 'libs' folder.
    2. Open the 'Properties' window of the project. Select the 'Java Build Path' option on the left-hand side menu, click on the 'Libraries' tab, and add the JAR references there.
    3. Configure 'AndroidManifest.xml' with permissions and receivers using the following code:
    4. <!-- Allows applications to connect network (Required) -->
      <uses-permission android:name="android.permission.INTERNET" />
      <!-- Allows applications to access information about networks (Required) -->
      <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
      <receiver
          android:name="com.contentstack.sdk.ConnectionStatus"
          android:enabled="true" >
          <intent-filter>
              <action android:name="android.net.conn.CONNECTIVITY_CHANGE" >
              </action>
          </intent-filter>
      </receiver>
      <receiver
          android:name="com.contentstack.sdk.ClearCache"
          android:enabled="true">
          <intent-filter>
              <action android:name="StartContentStackClearingCache">
              </action>
          </intent-filter>
      </receiver>

Initialize SDK

To initialize the SDK, specify application context, the API key, Delivery token, and environment name of the stack as shown in the snippet given below:

Stack stack = Contentstack.stack(context, "siteApiKey", "deliveryToken", "enviroment_name");

Once you have initialized the SDK, you can query entries to fetch the required content.

Cache Policies

The cache policies allow you to define the source from where the SDK will retrieve the content. Based on the selected policy, the SDK can get the data from cache, network, or both.

Let’s look at the various cache policies available for use:

POLICIES DESCRIPTION
NETWORK_ONLY (default) If you set NETWORK_ONLY as the cache policy, the SDK retrieves data through a network call, and saves the retrieved data in the cache. This is set as the default policy.
CACHE_ELSE_NETWORK If you set CACHE_ELSE_NETWORK as the cache policy, the SDK gets data from the cache. However, if it fails to retrieve data from the cache, it makes a network call.
NETWORK_ELSE_CACHE If you set NETWORK_ELSE_CACHE as the cache policy, the SDK gets data using a network call. However, if the call fails, it retrieves data from cache.
CACHE_ONLY If you set CACHE_ONLY as the cache policy, the SDK gets data from the cache.
CACHE_THEN_NETWORK If you set CACHE_THEN_NETWORK as the cache policy, the SDK gets data from cache, and then makes a network call. (A success callback will be invoked twice.)
IGNORE_CACHE If you set IGNORE_CACHE as the cache policy, the SDK always retrieves data by making a network call, without maintaining any cache.

You can set a cache policy on an entry, an asset, and/or a query object.

Setting a cache policy on an entry

This option allows you to set the cache policy to all the query objects of an entry.

public void entry_NETWORK_ONLY() {
    final Entry entry = stack.contentType("user").entry("blt11c1ad111ff1ddc1");
    entry.setCachePolicy(CachePolicy.NETWORK_ONLY);
    entry.addParam("key", "some_value");
    entry.fetch(new EntryResultCallBack() {
        @Override
        public void onCompletion(ResponseType responseType, Error error) {
            if (error == null) {
                //Success block
            } else {
                //Error block
            }
        }
    });
}

Setting a cache policy on an asset

This option allows you to set the cache policy to all the query objects of an asset.

public void assets_NETWORK_ONLY() {
    stack.assetLibrary().setCachePolicy(CachePolicy.NETWORK_ONLY);
    stack.assetLibrary().fetchAll(new FetchAssetsCallback() {
        @Override
        public void onCompletion(ResponseType responseType, List < Asset > assets, Error error) {
            if (error == null) {
                // Success block
            } else {
                // Failure block
            }
        }
    });
}

Setting a cache policy on a query object

This option allows you to set/override a cache policy on a specific query object.

public void query_NETWORK_ONLY() {
    Query query = stack.contentType("categories").query();
    query.where("uid", "blt11c1ad111ff1ddc1");
    query.setCachePolicy(CachePolicy.NETWORK_ONLY);
    query.find(new QueryResultsCallBack() {
        @Override
        public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) {
            if (error == null) {
                // Success block
            } else {
                // Failure block
            }
        }
    });
}

Basic Queries

Get a Single Entry

To retrieve a single entry from a content type use the code snippet given below:

ContentType contentType = stack.contentType("content_type_uid");
Entry blogEntry = contentType.entry("entry_uid");
blogEntry.fetch(new EntryResultCallBack() {
    @Override
    public void onCompletion(ResponseType responseType, Error error) {
        if (error == null) {
            // Success block
        } else {
            // Error block  
        }
    }
});

Get Multiple Entries

To retrieve multiple entries of a particular content type, use the code snippet given below:

//stack is an instance of Stack class
Query blogQuery = stack.contentType("content_type_uid").query();
blogQuery.find(new QueryResultsCallBack() {
    @Override
    public void onCompletion(ResponseType responseType, QueryResult queryResult, Error error) {
        if(error == null){
            //Success block
        }else{
            //Error block
        }
    }
});

These were example of some of the basic queries of the SDK. For advanced queries, refer to our API reference documentation by visiting the link given below.

Using the Sync API with Android SDK

The Sync API takes care of syncing your Contentstack data with your app and ensures that the data is always up-to-date by providing delta updates. Contentstack’s Android SDK provides several methods that you can use to sync data. Learn more about these methods below:

Using Persistence Library with Android SDK

The Persistence Library helps you save data on the local database of your app, and lets your app work offline as well. This library contains methods that are required to map fields of your content types and the device’s local storage (Realm).

API Reference

Go through our SDK API Reference guide to know about the methods that can be used to query your content in Contentstack.

Read Android API Reference Guide

Download SDK

The Android SDK interacts with and uses our Content Delivery APIs to fetch content from Contentstack. Download the SDK to deliver content to your Android projects.

Download Android SDK

Example Apps

To help you get started, we have created some sample applications that are powered by Contentstack Android SDK. Click on any of the links below to read the tutorials of the app, view app demo, or download the code from GitHub.

Was this article helpful?
top-arrow