harian untung99play.xyz

untung99play.xyz: How to Build Your First Android App Using an API

Untung99 menawarkan beragam permainan yang menarik, termasuk slot online, poker, roulette, blackjack, dan taruhan olahraga langsung. Dengan koleksi permainan yang lengkap dan terus diperbarui, pemain memiliki banyak pilihan untuk menjaga kegembiraan mereka. Selain itu, Untung99 juga menyediakan bonus dan promosi menarik yang meningkatkan peluang kemenangan dan memberikan nilai tambah kepada pemain.

Berikut adalah artikel atau berita tentang Harian untung99play.xyz dengan judul untung99play.xyz: How to Build Your First Android App Using an API yang telah tayang di untung99play.xyz terimakasih telah menyimak. Bila ada masukan atau komplain mengenai artikel berikut silahkan hubungi email kami di koresponden@untung99play.xyz, Terimakasih.

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

Steps to Build the Daily Horoscope App

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


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 opening tag.

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?) {

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


   val spinner = findViewById(R.id.spinner)
   val adapter = ArrayAdapter.createFromResource(this,R.array.sunsigns,android.R.layout.simple_spinner_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")


   } catch (e: Exception) {

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", "")
       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) {

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


Add the above two functions within the MainActivity class and replace the placeholder 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

   } catch (e: Exception) {
       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.

    Horoscope App
    Select the Sun sign
    Get Predictions
    Just an image

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.

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 , 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.


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