Build a Blog App for Android with Headless Oracle Content Management
Introduction
The Android development environment using Java or Kotlin can be a powerful tool for building applications that consume content from Oracle Content Management. Armed with the right content model, you can quickly build the Android user interface that makes up a typical blog app.
In this tutorial, we’ll build a simple blog application for Android using Kotlin by leveraging Oracle Content Management as a headless CMS. This Android sample is available on GitHub.
The tutorial consists of three steps:
Prerequisites
Before proceeding with this tutorial, we recommend that you read the following information first:
To follow this tutorial, you’ll need:
- an Oracle Content Management subscription
- an Oracle Content Management account with the Content Administrator role
- a Windows or Mac computer with Android tooling configured
- existing knowledge of Kotlin and Android programming as this tutorial assumes you already are familiar with common Android development concepts using Kotlin
What We’re Building
Our blog app consists of three screens that allow visitors to explore blog articles organized into topics. The first screen, the home screen, will consist of a list of blog topics.
To take a look at what we’re building, here’s the end state of our tutorial, a basic Android blog application that consumes content from Oracle Content Management.
This is what the home screen will look like at the end of this tutorial:
The second page, the topic screen, shows previews of each blog article that belongs to a topic. Here’s how an individual topic screen will look:
Lastly, the article screen renders the final blog article, including information about the blog’s author. Here’s how an individual article page will look:
To proceed, you’ll need to have an active subscription to Oracle Content Management and be logged in with the Content Administrator role.
Task 1: Prepare Oracle Content Management
If you don’t already have an Oracle Content Management instance, see the Quick Start to learn how to register for Oracle Cloud, provision an Oracle Content Management instance, and configure Oracle Content Management as a headless CMS.
For this tutorial, you’ll need to create a content model in either of two ways. There’s a downloadable asset pack available that will fill your empty repository with content types and associated content, or you can create your own content model and content.
To prepare Oracle Content Management:
- Create a channel and asset repository.
- Create a content model using either of two methods:
- Method 1: Import the Oracle Content Management Samples Asset Pack
- Method 2: Create your own content model
Create a Channel and Asset Repository
You first need to create a channel and an asset repository in Oracle Content Management so you can publish content.
To create a channel and an asset repository in Oracle Content Management:
Log in to the Oracle Content Management web interface as an administrator.
Choose Content in the left navigation menu and then choose Publishing Channels from the selection list in the page header.
In the upper right corner, click Create to create a new channel. Name the channel ‘OCEGettingStartedChannel’ for the purpose of this tutorial, and keep the access public. Click Save to create the channel.
Choose Content in the left navigation menu and then choose Repositories from the selection list in the page header.
In the upper right corner, click Create to create a new asset repository. Name the asset repository ‘OCEGettingStartedRepository’ for the purpose of this tutorial.
In the Publishing Channels field, select the OCEGettingStartedChannel channel to indicate to Oracle Content Management that content in the OCEGettingStartedRepository repository can be published to the OCEGettingStartedChannel channel. Click Save when you’re done.
Create a Content Model
The next step is to create a content model. You can use either of two methods:
- Method 1: Import the Oracle Content Management Samples Asset Pack
- Method 2: Create your own content model
Import the Oracle Content Management Samples Asset Pack
You can download a preconfigured Oracle Content Management sample assets pack that contains all required content types and assets for this tutorial. If you prefer, you can also create your own content model rather than download the sample assets pack.
You can upload a copy of the content we’re using in this tutorial from the Oracle Content Management Samples Asset Pack. This will let you experiment with the content types and modify the content. If you want to import the Oracle Content Management Samples Asset Pack, download the asset pack archive, OCESamplesAssetPack.zip, and extract it to a directory of your choice:
Download the Oracle Content Management Samples Asset Pack (OCESamplesAssetPack.zip) from the Oracle Content Management downloads page. Extract the downloaded zip file to a location on your computer. After extraction, this location will include a file called OCEGettingStarted_data.zip.
Log in to the Oracle Content Management web interface as an administrator.
Choose Content in the left navigation menu and then choose Repositories from the selection list in the page header. Now select OCEGettingStartedRepository and click the Import Content button in the top action bar.
Upload OCEGettingStarted_data.zip from your local computer to the Documents folder.
Once it’s uploaded, select OCEGettingStarted_data.zip and click OK to import the contents into your asset repository.
After the content has been imported successfully, navigate to the Assets page and open the OCEGettingStartedRepository repository. You’ll see that all the related images and content items have now been added to the asset repository.
Click Select All on the top left and then Publish to add all the imported assets to the publishing channel that you created earlier, OCEGettingStartedChannel.
Before publishing, you need to validate all the assets. First add OCEGettingStartedChannel as a selected channel, and then click the Validate button.
After the assets have been validated, you can publish all the assets to the selected channel by clicking the Publish button in the top right corner.
Once that’s done, you can see on the Assets page that all assets have been published. (You can tell by the icon above the asset name.)
After importing the Oracle Content Management Samples Asset Pack, you can start building the blog in Android.
Create Your Own Content Model
Instead of importing the Oracle Content Management Samples Asset Pack, you can also create your own content model.
For this tutorial, we’re using a content type called ‘OCEGettingStartedHomePage’ to build the home screen for our blog. This home page consists of a list of blog topics that should be included on the screen.
To create content types for the content model:
- Log in to the Oracle Content Management web interface as an administrator.
- Choose Content in the left navigation menu and then choose Asset Types from the selection list in the page header.
- Click Create in the top right corner.
- Choose to create a content type (not a digital asset type). Repeat this for all required content types.
We’ll create four content types, each with its own set of fields:
- OCEGettingStartedHomePage
- OCEGettingStartedTopic
- OCEGettingStartedAuthor
- OCEGettingStartedArticle
The first content type, OCEGettingStartedHomePage, should have the following fields:
Display Name | Field Type | Required | Machine Name |
---|---|---|---|
Company Name | Single-value text field | X | company_name |
Company Logo | Single-value text field | X | company_logo |
Topics | Multiple-value reference field | X | topics |
Contact URL | Single-value text field | X | contact_url |
About URL | Single-value text field | X | about_url |
This is what your OCEGettingStartedHomePage content type definition should look like:
The second content type, OCEGettingStartedTopic, should have the following field:
Display Name | Field Type | Required | Machine Name |
---|---|---|---|
Thumbnail | Single-value image field | X | thumbnail |
This is what your OCEGettingStartedTopic content type should look like:
The third content type, OCEGettingStartedAuthor, should have the following fields:
Display Name | Field Type | Required | Machine Name |
---|---|---|---|
Avatar | Single-value image field | X | avatar |
This is what your OCEGettingStartedAuthor content type should look like:
The fourth and final content type, OCEGettingStartedArticle, should have the following fields:
Display Name | Field Type | Required | Machine Name |
---|---|---|---|
Published Date | Single-value date field | X | published_name |
Author | Single-value reference field | X | author |
Image | Single-value image field | X | image |
Image Caption | Single-value text field | X | image_caption |
Article Content | Single-value large-text field | X | article_content |
Topic | Single-value reference field | X | topic |
This is what your OCEGettingStartedArticle content type should look like:
Once you’ve created your content types, you can add these content types to the repository that you created earlier, OCEGettingStartedRepository:
- Log in to the Oracle Content Management web interface as an administrator.
- Navigate to OCEGettingStartedRepository.
- Edit the repository and, under Asset Types, specify all four newly created content types. Click the Save button to save the changes.
After adding the content types to the repository, you can open the OCEGettingStartedRepository repository on the Assets page and start creating your content items for all the content types.
Task 2: Build the Blog Application in Android
To consume our Oracle Content Management content in an Android application, we can use the Android blog sample written in Kotlin, which is available as an open-source repository on GitHub.
Note: Remember that using the Android sample is optional, and we use it in this tutorial to get you started quickly. You can also build your own Android application in either Java or Kotlin as both are compatibile with the SDK.
Building the blog in Android consists of these steps:
- Clone the sample repository and Android SDK, and publish the SDK locally
- Configure the Android application
- Use the Oracle Content Management REST API to fetch content
Clone the Sample Repository and Android SDK, and Publish the SDK Locally
The Android blog sample is available as an open-source repository on GitHub.
You’ll first need to clone the sample from GitHub to your local computer as well as the Android SDK from GitHub, if you haven’t already.
Once you have your sample code and the SDK, in order to consume the Android SDK in the sample project, you should build and publish the SDK in your local Maven repository so that it can be consumed by the sample project. Open the Android SDK project in Android Studio and run the publishToMavenLocal
task to build and publish the SDK to your local Maven repository.
Open the Android sample in Android Studio
As with any Android application, you’ll need to import it into Android Studio, so that you can build and run it from there in an Android emulator or device. The sample code is already pre-configured with the server and publishing channel that are used to obtain data for the blog application.
Use the Oracle Content Management REST API to Fetch Content
The REST API for Content Delivery provides access to published assets in Oracle Content Management. Published assets include content items and digital assets, as well as their renditions. We can now leverage the REST API for Content Management to fetch content so that we can render it in our blog application.
The src/…/samples/blog/MainActivity.kt file has a function for creating the ContentDeliveryClient object, which is used to make calls to the REST API. The function below is a simplified version of the function from the sample application that shows the values being used.
fun createDeliveryClient() {
// preferences for cache
val cacheEnabled = true
// the server url and channel token for blog data
val serverUrl = "https://ocemobile-oce0002.cec.ocp.oraclecloud.com"
val channelToken = "b9ea60be0abf7255934cd2202fcf1314"
val settings = ContentSettings()
if (cacheEnabled) {
// enable caches, using default settings
.enableCache(appContext.cacheDir)
settings}
// SDK: create client API we'll use to make calls
=
deliveryClient .createDeliveryClient(
ContentSDK,
serverUrl,
channelToken)
settings}
The core classes used to get data to populate the blog sample application are under the “viewmodel” package and are suffixed with “Repository”. For example, the file HomePageRepository.kt contains methods to get data for the home page of the blog application including the list of topics displayed on the home page.
Home Page Data
The home page requires several data calls to get all of its data:
- First, we query for items in the channel matching the home page type.
- Then fetch the details for each of the topic items.
Below is the function that uses the SDK to fetch data for the home page. This function shows the values used, whereas the sample application function uses constants.
private fun getHomePage(): HomePage {
// SDK: create search request to get home page
val getHomePageRequest = SearchAssetsRequest(ContentApi.deliveryClient)
.type("OCEGettingStartedHomePage") // search by content type
.name("HomePage") // ...and by content name
.linksNone() // do not include links in the response
.fieldsAll() // do include all fields
val searchResult = getHomePageRequest.fetchResult()
// from the search result, only expect a single home page
val contentItems = searchResult.contentItems
// handle situation where no data is returned
if (contentItems.isNullOrEmpty())
throw ContentException(ContentException.REASON.itemNotFound, "No home page found for type")
// get first itme in home page data
val item = contentItems.first()
// convert list of ids into topic list
val topicList = item.getReferenceListIds("topics").map { Topic(it) }
// grab the topic type from one of the references
= item.getReferenceListField("topics").first().value.type
topicType
return HomePage(
= item.getTextField("company_name"),
companyName = item.getDigitalAssetField("company_logo").getThumbnailUrl(),
logoImageUrl = item.getTextField("contact_url"),
contactUrl = item.getTextField("about_url"),
aboutUrl = topicList.associateBy { it.id }) // convert list to map
topics
}
The SearchAssetsRequest object in the code above creates the request and the fetchResult() function will make a synchronous REST call similar to the request below to get the home page data.
GET content/published/api/v1.1/items?q=(type eq "OCEGettingStartedHomePage" AND name eq "HomePage")?fields=all&links=none&channelToken={channelToken}
Topic Page
The Articles screen shows all articles for a given topic. We use the same pattern as for the home page, but this time searching for content items of the type OCEGettingStartedArticle that reference the topic whose topic id is selected. This also shows how to make an asynchronous method call using the SDK. See the file ArticlesRepository.kt for more detail, but here’s the core method showing the pattern and values used.
// SDK: create search request to get all the articles
// sort by published_date field in descending order
val searchRequest = SearchAssetsRequest(ContentApi.deliveryClient)
.type("OCEGettingStartedArticle") // get "article" type
.fieldEquals("topic", topicId) // match topic id (e.g. drinks, recipes)
.sortByField("published_date") // sort by published date (optional)
.sortOrderDescending(true)
.linksNone() // no need for links (optional)
// SDK: make request to get articles using async callback method
.fetchAsync {response ->
searchRequest// successful SDK call?
if (response.isSuccess) {
// process the list and display in ui
} else {
// handle error case
}
}
Article Page
The individual article screen shows a single article, but the screen includes content from Author, which is a separate content type. To fetch one content item plus any content items it references, use the expand() method when creating the request object as shown below to get fields.author. Details are in AritcleDetailRepository.kt, but here’s the core code pattern:
// make a call to get the article, expanding the "author" field
val request = GetContentItemRequest(ContentApi.deliveryClient, articleId)
.expand("author") // only expand the author field
.linksNone()
// get the article detail as an asynchronous call
request.fetchAsync {response ->
// successful SDK call?
if (response.isSuccess) {
// process the list and display in ui
} else {
// handle error case
}
}
Now that we have our data queries, we can render the responses in our Android application UI.
Android ViewModel Classes
The blog application is structured as a standard ViewModel Android application. There are many online resources that describe how the ViewModel is used in Android and implemented in Kotlin.
Component Structure
There are three core classes for each screen in the application:
- the ViewModel class, which defines the structure of the data
- the Repository class, which makes the SDK call to fetch the data
- the Fragment class, which is responsible for populating the UI using the ViewModel class.
For example, the classes in the articles list screen are:
- ArticlesFragment
- ArticlesViewModel
- ArticlesRepository
Task 3: Prepare Your Application for Deployment
Now that we’ve built our Android blog application, we need to test it in a mobile emulator or device from Android Studio so we can debug any issues and preview the application before it goes live.
Conclusion
In this tutorial, we created a blog application for Android, which can be found on GitHub. This site uses Oracle Content Management as a headless CMS. After setting up and configuring Oracle Content Management with a channel of published content for the blog site tutorial, we installed and ran the Android site to fetch the required content and build the site.
Learn about important Oracle Content Management concepts in the documentation.
You can find more samples like this on the Oracle Content Management Samples page in the Oracle Help Center.
Build a Blog App for Android with Headless Oracle Content Management
F80569-01
May 2023
Copyright © 2021, 2023, Oracle and/or its affiliates.
Primary Author: Oracle Corporation