Steps to Integrate of Local Host with Android Kotlin
Last Updated :
30 Sep, 2024
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)
OUTPUTStep 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:
API integrated app
Similar Reads
Load PDF From URL in Android with Kotlin
PDF View is most of the applications to display the PDF files within the application to display the pdf within our own application rather than redirecting to another application. If we want to display multiple pdf files within our application we have to host these files and then access these files w
4 min read
Integrating JsonToKotlin Plugin With Android Studio
Android Studio is the best IDE for android development. Plenty of plugins are available and they can be installed easily via Android Studio itself. In computing, a plug-in is a software component that adds a particular characteristic to an existing computer program. When a program supports plug-ins,
5 min read
Chrome Custom Tabs in Android with Kotlin
As developers, we have the option of displaying web content to a user in their browser or via WebViews, but both have their own limitations: starting the browser is a large, non-customizable context transition for users, whereas WebViews don't support all aspects of the web platform. To address this
3 min read
Android Mastery with Kotlin: Beginner to Advanced
Are you looking to build your first Android app, or perhaps youâre a seasoned developer seeking to enhance your skills with a modern language? Have you heard about Kotlin but arenât sure why itâs become the preferred choice for Android development? With its clear syntax, powerful features, and seaml
5 min read
How to Send SMS in Android using Kotlin?
SMS Manager is a class in Android which is used to send the SMS to a specific contact from the android application. We can send text messages, data messages, and multimedia messages using this class. There are different methods that are provided to send different types of messages. In this article,
4 min read
How to Integrate Work Manager in Android?
In our day-to-day life, we are using apps like alarms, tasks reminders on our phones. Earlier running background tasks was a very tough task in Android but now with the help of Work Manager, we can schedule our tasks easily. Work Manager is a library of Android Jetpack. It allows the app to do thing
2 min read
How to Integrate MapmyIndia Maps in Android?
We will get to see many android applications displaying maps within their applications to display user locations or delivery boy locations within their application. We will get to see the applications using google maps or maps provided by Maps My India. Map My India is an SDK that provided the funct
4 min read
How to send message on WhatsApp in Android using Kotlin
Whatsapp is the one of most popular messaging App. Many android applications need the functionality to share some messages directly from their app to WhatsApp. For example, if a user wants to share the app or share a message from the app then this functionality comes in use. Either user can send a t
3 min read
How to Increase App Stability with Kotlin?
Kotlin is a new yet already mature programming language that aims to make developers happy. It's succinct, safe, and compatible with Java and other languages, with several methods to reuse code across platforms for productive work. We know from talking to the community that one of the primary motiva
4 min read
Retrofit with Kotlin Coroutine in Android
Retrofit is a type-safe http client which is used to retrieve, update and delete the data from web services. Nowadays retrofit library is popular among the developers to use the API key. The Kotlin team defines coroutines as âlightweight threadsâ. They are sort of tasks that the actual threads can e
3 min read