Android

How to Build Your First Android App (Using an API)

Are you an aspiring Android developer and thinking of building an Android App

Thousands of developers across the world are launching new apps on the Google play store every day. These apps range across various categories, from business to productivity, to games and utility apps. With over 105 billion app downloads in 2019, your app idea has great potential and a massive audience waiting to be tapped.

As easy as it may sound, building a mobile app still has challenges. Like any software, an app is also a piece of software with many internal components. These components need to be tightly integrated, without straining the mobile device for computation power and memory usage. That is where APIs play a significant role in easing the developer’s pain. 

In this blog post, we look at the nuances of building an Android application using an API. Apart from heavy lifting the resource-intensive tasks away from the phone, an API driven Android app embraces modular design. In this way, the responsibilities are shared between the app front end and the back end. Besides that, APIs offer a great way of adding real-time, data-driven features from external sources of information. 

View the Best Free APIs List

A Crash Guide On Android App Development Fundamentals

The Android operating system runs on the Linux kernel. For programming an Android app, you can use either Kotlin, Java, or C++. However, as of 2020, Kotlin is the preferred programming language recommended by Google. (Or learn how to build an Android App with Python).

Android App Components

Android has a well defined and modular architecture. It splits an app into different components. There are a few different categories of components defined within the Android environment.

  1. Activities: Activities represent the core interactions of the app. One activity is associated with a UI screen. An Android app is essentially a set of multiple activities stitched together via user-initiated navigation, to provide the various functions of the app.
  2. Services: Services are background tasks that perform some behind the scene operations for the app. They may also run while the app is minimized, or when the user is interacting with another app.
  3. Broadcast receivers: Broadcast receivers are like notifications that you receive on your mobile phone. These can be internally generated within the phone, such as alarm trigger or battery down indication. Broadcast receivers can also be attached to external events such as push notifications received from a cloud service.
  4. Content Providers: Content providers are the data stores that hold the app data. These can be filesystem resources, a database, or any form of persistent storage provided by the phone hardware.

For more detailed coverage on these components, check out the official application fundamentals guide in the Android developer portal. 

Most of the Android apps are built around a series of activities with one screen transitioning to/from the other. Activities are themselves composed of many kinds of UI components. They also follow a strict sequence of lifecycle events, which are triggered as callbacks. 

These callbacks provide developers with the means to handle events triggered in the activities. For example, when the app is launched, and the UI screen corresponding to the main activity is displayed, the onCreate( ) callback is triggered on the main activity. Subsequently, when the screen becomes invisible due to the transition to another screen, the onStop( ) callback is triggered.

For a better understanding of all the lifecycle events on an activity, refer to the official documentation on activity lifecycle

Simple Android apps can be built around a single activity, all other components being optional.

Android User Interaction

User interaction is at the core of any business logic implemented for an Android app.

The Android OS provides a framework for handling events. It provides a set of event listeners that can be registered for UI components. There are different types of event listeners defined for all forms of user inputs, such as click, touch, focus, or key presses. 

Here is how you would add a click handler to a button in Kotlin.

val button: Button = findViewById(R.id.corky)
button.setOnClickListener { view ->
    // do something when the button is clicked
}

Additionally, if you are creating your own custom UI components, then you can extend the default event callbacks by subclassing the base UI classes.  Some of the most frequently used event callback functions are:

onTouchEvent(MotionEvent) – Called when a touch screen motion event occurs.

onKeyDown(int, KeyEvent) – Called when a new key event occurs.

onKeyUp(int, KeyEvent) – Called when a key up event occurs.

onFocusChanged(boolean, int, Rect) – Called when the view gains or loses focus.

Calling an API from Android App

The Android SDK uses the HTTPURLConnection class from the Java standard library. With this class, you can configure the HTTP specific parameters such as the headers, method, cache, timeout settings, and more. 

To invoke an API, you have to use it in conjunction with URL and InputStreamReader.

url = URL("https://api.example.com/blah")

connection = url.openConnection() as HttpURLConnection

connection.requestMethod = "POST"

val `in` = connection.inputStream
val reader = InputStreamReader(`in`)

var data = reader.read()

Introducing the Daily Horoscope App Powered by Aztro API

Learning any new skill is best achieved by doing. Let’s show you how to build an Android app powered by an API. You can follow along the steps to replicate it within your development environment for the Android app.

Connect to the Aztro API
We are going to build a daily horoscope app. This is a simple app that displays the daily horoscope based on a sun sign selection on the app screen.

For this app, we have to rely on an external source for getting the horoscope predictions. APIs come to the rescue here. Using RapidAPI’s search feature, you can look up astrology related APIs for powering this app. 

We have chosen the aztro API for this purpose. But before you can start using the API, you have to follow a few steps to signup and activate your subscription.

Connect to the Aztro API

1. Sign up for RapidAPI Account

To access the Aztro API, you’ll first have to sign up for a free RapidAPI developer account. With this account, you get a universal API Key to access all APIs hosted in RapidAPI.

RapidAPI is the world’s largest API marketplace, with over 10,000 APIs and a community of over 1,000,000 developers. Our goal is to help developers find and connect to APIs to help them build amazing apps. 

2. Access the Aztro API

Once signed in, log in to your RapidAPI account. 

To access the API console of Aztro API, visit the API console here.

3. Subscribe to the Aztro API

Once inside the API console, click on the “Pricing” tab to access the pricing plan. 

Aztro API is a free API. You can subscribe to the “Mega” plan to get unlimited free access to the API.

 

4. Test the aztro API

After subscribing to the API, return to the “Endpoints” tab on the API console.

Now you are ready to test the API.  The Aztro API has only one endpoint. It expects a few parameters.

The ‘sign’ parameter indicates the sun sign name whose horoscope prediction you want to fetch from the API.  Optionally, you can add value for the ‘day’ parameter to specify the predictions for yesterday, today, or tomorrow. It defaults to the value of “today”. 

 

Trigger the API with the default values, and you will get an API response, somewhat like this.

As you can see, the API returns a few additional helpful pieces of information apart from the prediction.  

 You are all set to use this API within the Android app.

Connect to the Aztro API

How to Build an Android App with an API

Steps to Build the Daily Horoscope App

Now you are ready to build the Android app. It’s time to start coding.  

Prerequisites

Before getting into programming any Android app, you have to take care of a few prerequisites related to the Android app’s development and test setup.

  1. Install Android Studio: You must have the Android Studio version 3.0 or above, installed on your development computer.
  2. Install Android SDK: You must have the latest Android SDK (preferably Android 10.0) installed through the Android Studio.

Follow the first step below to set up a new app project within Android Studio. For all the subsequent steps, it is assumed that you have launched the Android Studio and are using it’s IDE interface to write the code.

Step 1: Start a new Kotlin project within the Android Studio.

Create a new project in the Android Studio with an empty activity.

After clicking “Next”, provide the app specific information as shown in the “Configure your project” dialog. Make sure to choose Kotlin as the Language. 

The save location can be anything as long as it is a valid path within your development environment. 

Wait for a few seconds. The Android Studio IDE will create a new project folder with a file explorer showing the project folder structure, 

Step 2: Add dependencies and additional configuration

This app uses the Kotlin coroutines for asynchronous execution. You have to add this as a dependency in the build.gradle(Module:app) file.  Locate the file in the Android Studio file explorer, under the  “Gradle Scripts” and open it. Add the following line within the “dependencies” section.

dependencies {
   .............
   .............
   implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.7'
}

As a standard practice for Android development, you also need to enable app permission for accessing the Internet to make API calls. Open the manifests/AndroidManifest.xml file and add the following line just after the <manifest> opening tag.

<uses-permission android:name="android.permission.INTERNET" /> 

Step 3: Open the MainActivity.kt file

The horoscope app has only one activity, which is the default Main activity. The MainActivity.kt is the source file of this activity. 

Open this file in the Android Studio editor.

For now, you can keep the auto-generated source code. From the next step onwards, we will modify it as per the horoscope app.

Step 4: Import the class libraries

Add a few more import statements at the top, after the package and existing import statement.  

import android.text.method.ScrollingMovementMethod
import android.view.View
import android.widget.*
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import org.json.JSONObject
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL

These import statements are used to import the UI widget and API call handling related classes from the standard library. The Kotlin coroutine is also imported.  

Step 5: Extend the MainActivity class and add instance variables

To add event listeners for item selection of sun signs, you need to extend the MainActivity as follows.

class MainActivity : AppCompatActivity(), AdapterView.OnItemSelectedListener{

}

For tracking the user selection and the API response, add two variables, sunSign and resultView.

class MainActivity : AppCompatActivity(), AdapterView.OnItemSelectedListener{

   var sunSign = "Aries"
   var resultView: TextView? = null

     …..
}

Step 6: Define the onCreate( ) function for MainActivity

Now you have to override the default onCreate( ) handler to add app-specific code for initializing the horoscope app.

Clear the default code for onCreate( ) and rewrite it as follows.

override fun onCreate(savedInstanceState: Bundle?) {
   super.onCreate(savedInstanceState)
   setContentView(R.layout.activity_main)

   var buttonView: Button = findViewById(R.id.button)
   button.setOnClickListener {
       GlobalScope.async {
           getPredictions(buttonView)
       }

   }

   val spinner = findViewById<Spinner>(R.id.spinner)
   val adapter = ArrayAdapter.createFromResource(this,R.array.sunsigns,android.R.layout.simple_spinner_item)
   adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
   spinner.adapter = adapter;
   spinner.onItemSelectedListener = this

   resultView = findViewById(R.id.resultView)

}

There are a few UI components added here. This includes a button to trigger the Aztro API, a dropdown spinner for the sun signs, and a result view for displaying the API response.

The click event of the button fires an async operation to call a function getPredictions( ) that you will implement in a little while.

Step 7: Implement the selection event handlers

Since the MainActivity inherited the OnItemSelectionListener interface,  you have to override a few of the callback functions to handle sun sign selection.

Add the following code below the onCreate( ) function.

override fun onNothingSelected(parent: AdapterView<*>?) {
   sunSign = "Aries"
}

override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
   if (parent != null) {
       sunSign = parent.getItemAtPosition(position).toString()
   }
}

The onNothingSelected( ) is the default state of selection, which sets the variable sunSign to a value to “Aries”.  The onItemSelected( ) is triggered to set the sunSign value to the one selected by the user.

Step 8: Implement the API call

The API is triggered by a button click whose handler we defined within the onCreate( ) function. Now it’s time to define the function getPredictions( ) and callAztroAPI( ) that triggers the API call.

public suspend fun getPredictions(view: android.view.View) {
   try {
       val result = GlobalScope.async {
           callAztroAPI("https://sameer-kumar-aztro-v1.p.rapidapi.com/?sign=" + sunSign + "&day=today")
       }.await()

       onResponse(result)

   } catch (e: Exception) {
       e.printStackTrace()
   }
}

private fun callAztroAPI(apiUrl:String ):String?{
   var result: String? = ""
   val url: URL;
   var connection: HttpURLConnection? = null
   try {
       url = URL(apiUrl)
       connection = url.openConnection() as HttpURLConnection
       // set headers for the request
       // set host name
       connection.setRequestProperty("x-rapidapi-host", "sameer-kumar-aztro-v1.p.rapidapi.com")

       // set the rapid-api key
       connection.setRequestProperty("x-rapidapi-key", "<YOUR_RAPIDAPI_KEY>")
       connection.setRequestProperty("content-type", "application/x-www-form-urlencoded")
       // set the request method - POST
       connection.requestMethod = "POST"
       val `in` = connection.inputStream
       val reader = InputStreamReader(`in`)

       // read the response data
       var data = reader.read()
       while (data != -1) {
           val current = data.toChar()
           result += current
           data = reader.read()
       }
       return result
   } catch (e: Exception) {
       e.printStackTrace()
   }

   // if not able to retrieve data return null
   return null

}

Add the above two functions within the MainActivity class and replace the placeholder <YOUR_RAPIDAPI_KEY> with your actual subscription key obtained from RapidAPI post the signup and subscription to the AztroAPI.

The getPredictions( ) function involves the callAztroAPI( ) function within the async coroutine and waits for it to return. 

The actual API invocation happens within callAztroAPI( ) via the HTTPURLConnection.  Before triggering the API, be sure to set the custom request headers “x-rapidapi-host”  and “x-rapidapi-key” as per the RapidAPI requirements. Additionally you have to set the “content-type” to “application/x-www-form-urlencoded”.

Step 9: Display horoscope prediction extracted from the API response

This is the last piece of code that you have to add. Define two new functions onResponse( ) and setText( ) as follows.

private fun onResponse(result: String?) {
   try {

       // convert the string to JSON object for better reading
       val resultJson = JSONObject(result)

       // Initialize prediction text
       var prediction ="Today's prediction nn"
       prediction += this.sunSign+"n"

       // Update text with various fields from response
       prediction += resultJson.getString("date_range")+"nn"
       prediction += resultJson.getString("description")

       //Update the prediction to the view
       setText(this.resultView,prediction)

   } catch (e: Exception) {
       e.printStackTrace()
       this.resultView!!.text = "Oops!! something went wrong, please try again"
   }
}

private fun setText(text: TextView?, value: String) {
   runOnUiThread { text!!.text = value }
}

The onResponse( ) also gets called from the getPredictions( ). It converts the API response to JSON format, extracts the value of prediction text, and prepares a string.

Finally, the resultView is updated with this string to display prediction on app screen.

Step 10: Add the UI View resources for MainActivity

The MainActivity is also associated with a view that displays the UI on the app screen. The view definition is in the form of XML files. 

Expand the res path under the Android Studio’s project file explorer to locate the xml files that you have to modify for this app.

Replace the strings.xml file with the following content.

<resources>
    <string name="app_name">Horoscope App</string>
    <string name="prompt_text">Select the Sun sign</string>
    <string name="submit_button">Get Predictions</string>
    <string name="background_description">Just an image</string>
    <string-array name="sunsigns">
        <item>Aries</item>
        <item>Taurus</item>
        <item>Gemini</item>
        <item>Cancer</item>
        <item>Leo</item>
        <item>Virgo</item>
        <item>Libra</item>
        <item>Scorpio</item>
        <item>Sagittarius</item>
        <item>Capricorn</item>
        <item>Aquarius</item>
        <item>Pisces</item>
    </string-array>
</resources>

This file contains the string constants for identifying all the sun signs. This is referenced in the MainActivity.kt for populating the dropdown. 

Now replace the entire activity_main.xml content with the code below.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/backgroundImageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:contentDescription="@string/background_description"
        android:scaleType="fitXY"
        android:scrollbars="vertical"
        android:visibility="visible"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/zodiac_portrait" />

    <TextView
        android:id="@+id/promptTextView"
        android:layout_width="296dp"
        android:layout_height="50dp"
        android:layout_marginTop="16dp"
        android:gravity="center_horizontal"
        android:text="@string/prompt_text"
        android:textColor="#FFFFFF"
        android:textSize="30sp"
        android:textStyle="bold"
        app:layout_constraintEnd_toStartOf="@+id/backgroundImageView"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toEndOf="@+id/backgroundImageView"
        app:layout_constraintTop_toTopOf="parent" />

    <Spinner
        android:id="@+id/spinner"
        android:layout_width="291dp"
        android:layout_height="48dp"
        android:layout_marginTop="35dp"
        android:background="@android:color/holo_blue_light"
        android:gravity="end"
        app:layout_constraintEnd_toStartOf="@+id/backgroundImageView"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toEndOf="@+id/backgroundImageView"
        app:layout_constraintTop_toBottomOf="@+id/promptTextView" />

    <Button
        android:id="@+id/button"
        android:layout_width="179dp"
        android:layout_height="59dp"
        android:layout_marginTop="177dp"
        android:background="#FF9800"
        android:onClick=""
        android:text="@string/submit_button"
        app:layout_constraintEnd_toStartOf="@+id/backgroundImageView"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toEndOf="@+id/backgroundImageView"
        app:layout_constraintTop_toTopOf="@+id/backgroundImageView"
        tools:ignore="OnClick" />

        <TextView
            android:id="@+id/resultView"
            android:layout_width="309dp"
            android:layout_height="417dp"
            android:layout_marginTop="260dp"
            android:layout_marginEnd="39dp"
            android:layout_marginRight="39dp"
            android:foregroundGravity="fill_horizontal"
            android:justificationMode="inter_word"
            android:textSize="18sp"
            android:textStyle="bold"
            android:textColor="#FFFFFF"
            android:visibility="visible"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintEnd_toStartOf="@+id/backgroundImageView"
            app:layout_constraintHorizontal_bias="0.5"
            app:layout_constraintStart_toEndOf="@+id/backgroundImageView"
            app:layout_constraintTop_toTopOf="@+id/backgroundImageView" />

</androidx.constraintlayout.widget.ConstraintLayout>

The activity_main.xml file contains the layout definition of the UI elements and their properties. It also includes their display properties. For a detailed overview of view layouts in Android, take a look at the official layouts guide.   

The layout definition contains an XML tag called <ImageView>, representing a background image in the MainActivity. Place the below image inside the res/drawable path within the save location of the app project, and rename it as zodiac_portrait.png.  

This image will be referenced by the MainActivity screen and rendered as the app background image. 

Android Studio also provides a design preview of your App screen layout based on the layout definition. This preview gives a fair idea about how the screen will appear in runtime.

You are all done with programming the app.

Step 11: Building and testing the horoscope app

Make sure that you save all the files that are modified in the previous steps.

 Now it’s time to build and run the app. On the Android Studio, choose the “Run > Run `app`” submenu. This will build the app code and subsequently launch the Horoscope app on a device emulator. The emulator takes some time to initialize the first time. 

Once the app is up and running, interact with it, and check out the predictions for different sun signs.

If you want to test this app on a real Android phone, check out the official Android guide on building and running your app, and testing on a hardware device.

Conclusion

Congratulations! You have now mastered the skill of building an Android app powered by an API. Now you can list it on the Google Play Store.

With the help of RapidAPI’s API marketplace, you can look up thousands of APIs that can be integrated with Android apps for performing various utility tasks ranging from language translation, location-based services, weather predictions, and more. So go ahead, explore the APIs, and good luck for your next Android project. 

View the Best Free APIs List

4/5 - (3 votes)

View Comments

  • Sir,

    Your explanation is very useful and up to the point, especially for beginners like me. Could you please post a tutorial how to retrieve data from an sql server and show using the Aztro API.

    Thanks a lot.

    Fysal Usman

  • Very good blog. I think developers who are freshers who are working in an android app development companywill like this blog. Anyways, thanks for the blog. Will share it with my peers and friends. Kudos.

Share
Published by

Recent Posts

Power Up Your Enterprise Hub: New March Release Boosts Admin Capabilities and Streamlines Integrations

We're thrilled to announce the latest update to the Rapid Enterprise API Hub (version 2024.3)!…

2 weeks ago

Unveiling User Intent: How Search Term Insights Can Empower Your Enterprise API Hub

Are you curious about what your API consumers are searching for? Is your Hub effectively…

2 weeks ago

Rapid Enterprise API Hub Levels Up Custom Branding, Monetization, and Management in February Release

The RapidAPI team is excited to announce the February 2024 update (version 2024.2) for the…

4 weeks ago

Supercharge Your Enterprise Hub with January’s Release: Search Insights, Login Flexibility, and More!

This January's release brings exciting features and improvements designed to empower you and your developers.…

3 months ago

Enhanced Functionality and Improved User Experience with the Rapid API Enterprise Hub November 2023 Release

Rapid API is committed to providing its users with the best possible experience, and the…

5 months ago

The Power of Supporting Multiple API Gateways in an API Marketplace Platform

In today's fast-paced digital world, APIs (Application Programming Interfaces) have become the backbone of modern…

6 months ago