Contentstack Delivery Android SDK

View as Markdown

Overview

This reference covers the public API of the com.contentstack.sdk:android package, with one page per class. Use it to look up parameters, return types, validation behavior, and worked examples for every object you reach from Contentstack.stack.

Before you begin This reference assumes you have installed and initialized the SDK. If you have not, complete the Get Started with Android SDK guide first. This SDK requires Android API level 24 (Android 7.0) or later, and Java 17, the Java version the SDK compiles to. This reference documents version 4.4.0 (com.contentstack.sdk:android:4.4.0), and the changelog lists behavior changes between releases.

Known issue In 4.4.0, the published package does not include its region list, so creating the stack on the main thread fails unless you call setHost. Without a host, Contentstack.stack downloads the list on the calling thread. On the main thread Android blocks the download, and stack throws IllegalStateException, then throws it again on every later call in the process. Call config.setHost(...) with your region's host, or create the stack on a background thread. Every example in this reference passes a Config with setHost for this reason. The host of the US region is cdn.contentstack.io, and the setRegion method lists the host of every other region. The setHost method describes the host format.

Minimum Working Example

The snippet below creates a stack, fetches one entry, and logs its title, or the Error the callback receives when the request fails.

import android.util.Log;

import com.contentstack.sdk.Config;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Entry;
import com.contentstack.sdk.EntryResultCallBack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;

try {
    Config config = new Config();
    config.setHost("cdn.contentstack.io"); // your region's host, see Config setHost
    Stack stack = Contentstack.stack(context, "<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>", config);
    Entry entry = stack.contentType("<CONTENT_TYPE_UID>").entry("<ENTRY_UID>");
    entry.fetch(new EntryResultCallBack() {
        @Override
        public void onCompletion(ResponseType responseType, Error error) {
            if (error == null) {
                Log.d("Contentstack", entry.getTitle());
            } else {
                // The API rejected the request or the network failed
                Log.e("Contentstack", "Request failed: " + error.getStatusCode() + " "
                        + error.getErrorCode() + " " + error.getErrorMessage());
            }
        }
    });
} catch (Exception e) {
    // Contentstack.stack throws when a credential is null
    Log.e("Contentstack", "Setup failed: " + e.getMessage());
}

The snippet runs inside a method of an Android component, where context is an Android Context, for example the value of getApplicationContext() in an Activity.

SDK Structure

The SDK uses a builder pattern. Contentstack.stack takes your credentials and a Config, and returns a Stack. Each factory call on the stack returns an object for a narrower scope, such as one content type, one entry, or a query. Builder methods on that object store a value and return the same object, so you can chain them. Every chain starts at the Stack.

The terminal calls below send the request and pass the result to a callback:

  • fetch on Entry, Asset, ContentType, and GlobalField
  • find and findOne on Query
  • fetchAll on AssetLibrary, and findAll on GlobalField
  • find on Taxonomy
  • the sync methods and getContentTypes on Stack

Because builder methods do not check their values against the API, an invalid value fails on the terminal call, not where you passed it. It surfaces as an Error in the callback. A terminal call also returns before the response arrives, so read the result, and the getters of the object you fetched, inside the callback. The Validation section of each method page names the terminal call that reports its errors.

Besides the request classes, Group, Error, and the JSON Rich Text Editor (JSON RTE) classes work on data already in memory and send no request.

Class Overview

Set up the SDK.

ClassRoleAccessed via
ContentstackThe static entry point that creates a stack and looks up service URLs by region.Contentstack.stack(...)
ConfigThe region, host, branch, early access, proxy, and connection pool settings of a stack.new Config()
StackOne stack and environment, and the start of every chain.Contentstack.stack(context, ...)
EndpointA static resolver of Contentstack service URLs for a region.Endpoint.getContentstackEndpoint(...)

Read content types and entries.

ClassRoleAccessed via
ContentTypeOne content type and its schema.stack.contentType(uid)
EntryOne published entry of a content type.contentType.entry(uid)
QueryA filtered list of the published entries of one content type.contentType.query()
QueryResultThe entries, count, and content type that a query returns.onCompletion(..., QueryResult queryresult, ...)
GroupThe value of one Group field of a fetched entry.entry.getGroup(key)

Read assets and global fields.

ClassRoleAccessed via
AssetOne published asset.stack.asset(uid)
AssetLibraryThe list of published assets in the stack.stack.assetLibrary()
GlobalFieldOne global field and its schema, or the list of global fields.stack.globalField(uid)

Filter by taxonomy and sync content.

ClassRoleAccessed via
TaxonomyA filter that returns the published entries tagged with taxonomy terms.stack.taxonomy()
SyncStackOne page of a sync response, with its tokens.onCompletion(SyncStack syncStack, ...)

Handle errors.

ClassRoleAccessed via
ErrorThe reason a request failed, which the SDK passes to the callback.onCompletion(..., Error error)

Render JSON RTE fields.

ClassRoleAccessed via
OptionThe interface the SDK calls to turn JSON RTE content into HTML.SDKUtil.jsonToHTML(..., option)
DefaultOptionThe implementation of Option that the SDK provides.new DefaultOption()
NodeToHTMLA static converter of one JSON RTE text node to HTML.NodeToHTML.textNodeToHTML(...)
MetadataThe details of one entry or asset embedded in a JSON RTE field.new Metadata(...)

Task Index

TaskStart hereClass
Fetch one entry by UIDfetchEntry
Filter entries by a field valuewhereQuery
Page through the entries of a content typeskipQuery
Return referenced entries in fullincludeReferenceEntry
Read an entry in another localesetLocaleEntry
Read an entry from the cache when the device is offlinesetCachePolicyEntry
List the published assets in the stackfetchAllAssetLibrary
Filter entries by a taxonomy term and the terms below itequalAndBelowTaxonomy
Sync all published content, then only what changedsyncStack
Build a resized or converted image URLImageTransformStack
Render a JSON RTE field as HTMLOptionOption
Set the region, host, or branchConfigConfig

Key Usage Patterns

Each example below is a complete Java snippet with its own imports, stack, and Config with setHost. Paste it into a method of an Android component.

Filter entries by a field and resolve their references

import android.util.Log;

import com.contentstack.sdk.Config;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Entry;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.Query;
import com.contentstack.sdk.QueryResult;
import com.contentstack.sdk.QueryResultsCallBack;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;

import org.json.JSONArray;

try {
    Config config = new Config();
    config.setHost("cdn.contentstack.io"); // your region's host, see Config setHost
    Stack stack = Contentstack.stack(context, "<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>", config);
    // The builder methods store values. find sends the request.
    Query query = stack.contentType("<CONTENT_TYPE_UID>").query()
            .where("category", "news")
            .includeReference("author")
            .descending("updated_at")
            .limit(10);
    query.find(new QueryResultsCallBack() {
        @Override
        public void onCompletion(ResponseType responseType, QueryResult queryResult, Error error) {
            if (error != null) { Log.e("Contentstack", error.getErrorMessage()); return; }
            for (Entry entry : queryResult.getResultObjects()) {
                JSONArray author = entry.getJSONArray("author");
                Log.d("Contentstack", entry.getTitle() + " by " + author);
            }
        }
    });
} catch (Exception e) {
    Log.e("Contentstack", e.getMessage());
}

Page through every entry of a content type

The SDK sends one request per find call and does not request further pages. The callback below requests each next page with a new query, and stops at the count that includeCount adds.

import android.util.Log;

import com.contentstack.sdk.Config;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Entry;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.QueryResult;
import com.contentstack.sdk.QueryResultsCallBack;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;

import java.util.ArrayList;
import java.util.List;

try {
    Config config = new Config();
    config.setHost("cdn.contentstack.io"); // your region's host, see Config setHost
    Stack stack = Contentstack.stack(context, "<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>", config);
    int pageSize = 25;
    stack.contentType("<CONTENT_TYPE_UID>").query()
            .includeCount().skip(0).limit(pageSize)
            .find(new QueryResultsCallBack() {
                private final List<Entry> entries = new ArrayList<>();

                @Override
                public void onCompletion(ResponseType responseType, QueryResult queryResult, Error error) {
                    if (error != null) { Log.e("Contentstack", error.getErrorMessage()); return; }
                    List<Entry> page = queryResult.getResultObjects();
                    entries.addAll(page);
                    if (page.isEmpty() || entries.size() >= queryResult.getCount()) {
                        Log.d("Contentstack", "Read " + entries.size() + " entries");
                        return;
                    }
                    // A new query for the next page, answered by this same callback
                    stack.contentType("<CONTENT_TYPE_UID>").query()
                            .includeCount().skip(entries.size()).limit(pageSize)
                            .find(this);
                }
            });
} catch (Exception e) {
    Log.e("Contentstack", e.getMessage());
}

Show cached content first, then the network result

With CACHE_THEN_NETWORK, the callback fires once with ResponseType.CACHE when a cached copy exists, then once with ResponseType.NETWORK. The snippet below handles both calls.

import android.util.Log;

import com.contentstack.sdk.CachePolicy;
import com.contentstack.sdk.Config;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Entry;
import com.contentstack.sdk.EntryResultCallBack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;

try {
    Config config = new Config();
    config.setHost("cdn.contentstack.io"); // your region's host, see Config setHost
    Stack stack = Contentstack.stack(context, "<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>", config);
    Entry entry = stack.contentType("<CONTENT_TYPE_UID>").entry("<ENTRY_UID>");
    entry.setCachePolicy(CachePolicy.CACHE_THEN_NETWORK);
    entry.fetch(new EntryResultCallBack() {
        @Override
        public void onCompletion(ResponseType responseType, Error error) {
            if (error != null) { Log.e("Contentstack", error.getErrorMessage()); return; }
            // The callback runs on the main thread, so it can update views directly
            Log.d("Contentstack", "Source: " + responseType + ", title: " + entry.getTitle());
        }
    });
} catch (Exception e) {
    Log.e("Contentstack", e.getMessage());
}

Filter entries by a taxonomy term on a background thread

Taxonomy.find runs the request on the thread that calls it and throws NetworkOnMainThreadException on the main thread. The snippet below calls it from a new thread, and catches the RuntimeException that find throws when no response arrives.

import android.util.Log;

import com.contentstack.sdk.Config;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.Stack;
import com.contentstack.sdk.Taxonomy;
import com.contentstack.sdk.TaxonomyCallback;

import org.json.JSONArray;
import org.json.JSONObject;

try {
    Config config = new Config();
    config.setHost("cdn.contentstack.io"); // your region's host, see Config setHost
    Stack stack = Contentstack.stack(context, "<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>", config);
    Taxonomy taxonomy = stack.taxonomy().equalAndBelow("taxonomies.<TAXONOMY_UID>", "<TERM_UID>");

    // find blocks the calling thread, so run it off the main thread
    new Thread(() -> {
        try {
            taxonomy.find(new TaxonomyCallback() {
                @Override
                public void onResponse(JSONObject response, Error error) {
                    if (error != null) { Log.e("Contentstack", error.getErrorMessage()); return; }
                    JSONArray entries = response.optJSONArray("entries");
                    Log.d("Contentstack", "Entries: " + (entries == null ? 0 : entries.length()));
                }
            });
        } catch (RuntimeException e) {
            // find throws when the request gets no response
            Log.e("Contentstack", e.getMessage());
        }
    }).start();
} catch (Exception e) {
    Log.e("Contentstack", e.getMessage());
}

Sync only the content that changed since the last run

Run sync once to read everything, and store the sync token from its last page. On later runs, pass that token to syncToken. The SDK requests every page for you and calls the callback once per page.

import android.util.Log;

import com.contentstack.sdk.Config;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.Stack;
import com.contentstack.sdk.SyncResultCallBack;
import com.contentstack.sdk.SyncStack;

import org.json.JSONObject;

import java.util.ArrayList;

try {
    Config config = new Config();
    config.setHost("cdn.contentstack.io"); // your region's host, see Config setHost
    Stack stack = Contentstack.stack(context, "<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>", config);
    stack.syncToken("<SYNC_TOKEN>", new SyncResultCallBack() {
        @Override
        public void onCompletion(SyncStack syncStack, Error error) {
            if (error != null) { Log.e("Contentstack", error.getErrorMessage()); return; }
            ArrayList<JSONObject> items = syncStack.getItems();
            Log.d("Contentstack", "Changed items on this page: " + (items == null ? 0 : items.size()));
            if (syncStack.getSyncToken() != null) {
                // Last page: store this token for the next run
                Log.d("Contentstack", "Next sync token: " + syncStack.getSyncToken());
            }
        }
    });
} catch (Exception e) {
    Log.e("Contentstack", e.getMessage());
}

Retry a rate-limited request with a delay

The SDK sends each request once. The callback below checks for a 429 status and sends the same request again after a delay that grows with each attempt.

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.contentstack.sdk.Config;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Entry;
import com.contentstack.sdk.EntryResultCallBack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;

try {
    Config config = new Config();
    config.setHost("cdn.contentstack.io"); // your region's host, see Config setHost
    Stack stack = Contentstack.stack(context, "<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>", config);
    Entry entry = stack.contentType("<CONTENT_TYPE_UID>").entry("<ENTRY_UID>");
    Handler handler = new Handler(Looper.getMainLooper());
    entry.fetch(new EntryResultCallBack() {
        private int attempt = 1;

        @Override
        public void onCompletion(ResponseType responseType, Error error) {
            if (error == null) {
                Log.d("Contentstack", entry.getTitle());
                return;
            }
            if (error.getStatusCode() == 429 && attempt < 3) {
                // Wait one second, then two, and send the same request again
                long delayMs = 1000L * attempt;
                attempt++;
                handler.postDelayed(() -> entry.fetch(this), delayMs);
                return;
            }
            Log.e("Contentstack", error.getErrorMessage());
        }
    });
} catch (Exception e) {
    Log.e("Contentstack", e.getMessage());
}

SDK-Wide Notes

ConcernBehaviorDefault when unset
AuthenticationContentstack.stack takes the API key, delivery token, and environment, and the SDK sends them as the api_key, access_token, and environment headers on every request. No other method takes credentials.Not applicable. stack throws NullPointerException for a null credential and declares throws Exception, so every call needs a try block.
Failed requestsNo request method throws when the API rejects a request or the network fails. The callback receives a non-null Error and an empty result, and error is null on success. Taxonomy find differs in two ways: its Error carries only the message and code, and a request with no response throws RuntimeException.Not applicable. With no response, for example on a timeout, getStatusCode() and getErrorCode() return 0.
Callback threadThe SDK calls every callback on the main thread, so onCompletion can update views. Taxonomy.find runs the request and its callback on the calling thread and throws NetworkOnMainThreadException on the main thread, so call it from a background thread.The main thread. Taxonomy uses the thread that calls find.
Regions and endpointsCall setRegion or setHost on a Config and pass it to Contentstack.stack. A host from setHost always wins over the region, and in 4.4.0 setHost avoids the Known issue above.ContentstackRegion.US, which uses the host cdn.contentstack.io.
BranchesCall setBranch on the Config. The SDK sends the value as the branch header on every request from the stack.No branch header.
Rate limiting and retryThis SDK does not auto-retry on 429, so implement backoff in your calling code. Each request makes one attempt, also on a 5xx status or a timeout.No retry.
TimeoutsEach request times out after 30 seconds, and no method changes it. Taxonomy requests use the OkHttp defaults of 10 seconds to connect, read, and write.30000 ms.
Proxy and connection poolsetProxy and connectionPool apply only to Taxonomy requests, and the proxy also applies to the region list download. Entry, query, asset, content type, global field, and sync requests ignore both settings.No proxy, and the OkHttp default pool of up to 5 idle connections kept for 5 minutes.
CachingEntry, Query, Asset, and AssetLibrary take a CachePolicy through setCachePolicy, and responseType in the callback reports NETWORK, CACHE, or UNKNOWN. Each Contentstack.stack call schedules a daily cleanup that deletes cached responses 24 hours old or older.Each class has its own default. Entry uses NETWORK_ONLY, Query stores null and treats it as NETWORK_ONLY, and Asset and AssetLibrary use IGNORE_CACHE. The setCachePolicy method of each class changes it: Entry setCachePolicy, Query setCachePolicy, Asset setCachePolicy and AssetLibrary setCachePolicy.
Android permissionsThe SDK manifest declares the INTERNET and ACCESS_NETWORK_STATE permissions, and the Android build merges them into your app manifest.Both permissions. The Android build adds them to your app.

Warning This SDK requires a delivery token, which it sends as the access_token header. Contentstack.stack does not check the token against the API, so a management token or a preview token in its place fails at the first request with an Error in the callback. This SDK has no Live Preview support and takes no preview token. Refer to Content Delivery API Errors for the full error code list.

SDK Limitations

CapabilitySupportedNotes / Alternative
Catch an API rejection as an exceptionNoCheck the Error argument in the callback, as the Minimum Working Example above does.
Retry a rate-limited or failed request automaticallyNoCheck getStatusCode() in the callback and send the request again after a delay, as in Key Usage Patterns above.
Change the request timeoutNoNone. Requests time out after 30 seconds, and Taxonomy requests use the OkHttp defaults.
Route entry, query, asset, or sync requests through a proxyNoNone in this SDK. setProxy applies to Taxonomy requests and the region list download only.
Read every page of a list in one callNoLoop with skip and limit on a new query per page, as in Key Usage Patterns above. The sync methods of Stack are the exception and request every page. AssetLibrary has no skip or limit and returns the first 100 assets.
Show draft content through Live PreviewNoNone in this SDK. It reads published content with a delivery token.