Open In App

Steps to Integrate of Local Host with Android Kotlin

Last Updated : 30 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will build an Android app using Kotlin that connects to a local host server. You will learn how to configure your development environment, set up a local host server on your machine, and make network requests from the Android app. By the end of this article, you’ll have a fully functional app that communicates with a local backend server, enabling you to test APIs and backend logic without deploying to a live environment.

Note: make sure the hosting server device and the client device must be on the same network and none of them should be the source of the network.

Step by Step Implementation of Integration of Local Host with Android Kotlin

Let us check Steps to Implementation of Integration of Local Host are mentioned below:

Step 1: Install Express and CORS

To set up a Node.js backend, install Express with npm install express to handle routing and server-side functionalities, and CORS with npm install cors to manage cross-origin requests. Express simplifies building web applications, while CORS allows your server to handle requests from different domains, essential for frontend-backend communication.

npm install express
npm install cors

Step 2: Implement the Code Below in your server.js or app.js

Javascript
const express = require("express")
const cors = require("cors")

const app = express()
app.use(express.json())

app.use(cors())

Step 3: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.

Note: Select Kotlin as the programming language.

Step 4: In the Android app manifest, add the Internet permission.

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

Step 5: In the manifest, within the <application> element, add android:usesCleartextTraffic="true".

XML
<application
        ...   
        android:usesCleartextTraffic="true" <!--ADD THIS-->
        ...
        <activity
            android:name=".MainActivity"
            ...
        </activity>
    </application>

Step 6: Add the Retrofit dependency in build.gradle (Module: app).

// Retrofit Gson Converter: This dependency allows Retrofit to automatically convert JSON responses into Kotlin objects using Gson.
implementation("com.squareup.retrofit2:converter-gson:2.9.0")

// Retrofit Core Library: This is the core Retrofit library used for making HTTP requests in Android.
implementation("com.squareup.retrofit2:retrofit:2.9.0")

Step 7: Create a data class (Responses.kt) for defining the response that you get from the API.

// Json response we are getting
{response : "API call successful" }

Note: The variable name defined in the data class and the key of the JSON response must be the same in order to receive the response from the API.

Responses.kt
data class Responses(val response: String)

Step 8: Create an API interface (ApiService.kt) in which you define your functions and methods of the API interface.

ApiService.kt
import retrofit2.Call
import retrofit2.http.GET

// Define the ApiService interface to outline the API endpoints and methods for Retrofit.
interface ApiService {

    // Define a GET request for the endpoint "api/getCall".
    // This method will return a Call object wrapping the Responses class.
    @GET("api/getCall")
    fun getCall(): Call<Responses>

}

Step 9: Create an object file (RetrofitBuilder.kt) for building Retrofit to make API calls.

RetrofitBuilder.kt
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

// Singleton object to manage Retrofit instance creation and configuration.
object RetrofitBuilder {

    // Create and configure the Retrofit instance.
    private val retrofit = Retrofit.Builder()
        .baseUrl("http://localhost:3000/")  // Base URL for API requests. 'localhost' should be replaced with your system's IPv4 address
        .addConverterFactory(GsonConverterFactory.create())  // Add GsonConverterFactory to convert JSON responses to Kotlin objects.
        .build()  // Build the Retrofit instance.

    // Create an implementation of the ApiService interface using the Retrofit instance.
    val api = retrofit.create(ApiService::class.java)
}

Step 10: To get your system's IPv4 address. Run below mentioned command inside your terminal.

ipconfig (For windows)
ifconfig (For mac)
comand
OUTPUT

Step 11: Inside Android Studio, add the following XML code in your layout XML file.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- Root element of the layout -->4
<LinearLayout 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"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="30dp"
        android:text="Hello World!"
        android:textSize="25dp" />
	<!-- Button to trigger an API call -->
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="30dp"
        android:text="API CALL" />

</LinearLayout>

Step 12: Now, add the following code inside your MainActivity.kt file.

MainActivity.kt
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.basicproject.databinding.ActivityMainBinding
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class MainActivity : AppCompatActivity() {

  	// Late initialization of the view binding
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
		
        // Inflate the layout using view binding
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        
		// Set a click listener on the button
        binding.button.setOnClickListener {
			
          	// Make a network call using Retrofit
            RetrofitBuilder.api.getCall().enqueue(object : Callback<Responses> {
                override fun onResponse(call: Call<Responses>, response: Response<Responses>) {
					
                  	// Check if the response code is 200 (success)
                    if (response.code() == 200) {
                        val responseBody = response.body()
                        // If the response body is not null, update the TextView with the response
                        if (responseBody != null) {
                            binding.textView.text = response.body()!!.response
                        }
                    }
                }
				
                // Handle a failed network call
                override fun onFailure(call: Call<Responses>, t: Throwable) {
                  	// Update the TextView with the error message
                    binding.textView.text = t.message.toString()
                }

            })
        }
    }
}

Output of the Application:

apicalls
API integrated app



Next Article

Similar Reads