User registration – Kotlin, Node JS, Mongo DB

This tutorial will create an android user registration activity in Kotlin. You will learn the following:

  • How to use Node JS API for android apps
  • How to call HTTP request with POST method in Kotlin

Creating an activity

First, we will create an empty activity named “RegisterActivity.kt”. Following will be the code of that file:

package com.adnantech.myapp

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity

class RegisterActivity : AppCompatActivity() {

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

This will look for a file named “activity_register.xml” inside the “res/layout” folder.

Create an XML file

Then we will create a file named “activity_register.xml” inside the “res/layout” folder. That file will have the following code:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="20dp">

    <TextView
        android:id="@+id/heading"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Register"
        android:textAlignment="center"
        android:textSize="40sp"
        android:textStyle="bold" />

    <EditText
        android:id="@+id/etName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/heading"
        android:layout_marginTop="20dp"
        android:hint="Enter name" />

    <EditText
        android:id="@+id/etPhone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/etName"
        android:layout_marginTop="20dp"
        android:hint="Enter phone"
        android:inputType="phone" />

    <EditText
        android:id="@+id/etPassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/etPhone"
        android:layout_marginTop="20dp"
        android:hint="Enter password"
        android:inputType="textPassword" />

    <Button
        android:id="@+id/btnRegister"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/etPassword"
        android:layout_marginTop="20dp"
        android:text="Register" />

</RelativeLayout>

It will display the heading “Register” horizontally center-aligned. Three input fields. One to enter the name, one for the phone number, and one for the password. It will also display a button that when clicked will call an HTTP request to save that data.

Button onclick event listener

We need to attach an “onclick” event listener to the button. So we will create instances of all our input fields and button.

class RegisterActivity : AppCompatActivity() {

    private lateinit var etName: EditText
    private lateinit var etPhone: EditText
    private lateinit var etPassword: EditText
    private lateinit var btnRegister: Button

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

        etName = findViewById(R.id.etName)
        etPhone = findViewById(R.id.etPhone)
        etPassword = findViewById(R.id.etPassword)
        btnRegister = findViewById(R.id.btnRegister)

        btnRegister.setOnClickListener {
            doRegister()
        }
    }

    private fun doRegister() {
        // [HTTP request code goes here]
    }
}

And inside this button click listener, we are calling our method that will call an HTTP request.

Calling an HTTP request

To call an HTTP request, first, make sure you have INTERNET and ACCESS_NETWORK_STATE permissions added in your “AndroidManifest.xml” file.

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

Then you need to add the following line in your “app/build.gradle” file:

implementation "com.android.volley:volley:1.2.1"

Make sure to “Gradle sync” after pasting that line. You will see the option to sync Gradle on top in Android studio. After that, you need to write the following code in the [HTTP request code goes here] section:

btnRegister.isEnabled = false

val queue = Volley.newRequestQueue(this)
val url = "http://172.20.10.4:3000/register"

val requestBody =
    "name=" + etName.text + "&phone=" + URLEncoder.encode(etPhone.text.toString(), "UTF-8") + "&password=" + etPassword.text
val stringReq: StringRequest =
    object : StringRequest(Method.POST, url,
        Response.Listener { response ->
            btnRegister.isEnabled = true
            Log.i("mylog", response)
        },
        Response.ErrorListener { error ->
            Log.i("myLog", "error = " + error)
        }
    ) {
        override fun getBody(): ByteArray {
            return requestBody.toByteArray(Charset.defaultCharset())
        }
    }
queue.add(stringReq)

This will first disable the registration button. Then it will create an instance of Volley. After that, it sets the path of an API. You can get your IP address by running either of the following commands in your terminal:

> ipconfig /all
or
> ifconfig

You need to copy the ipv4 address and paste it as your IP address.

Then it creates a request body, the parameters that will be sent to the API. Creates an instance of “StringRequest”. When the response is received, it simply enables the registration button and displays the response in the log. You can view the response by opening your “logcat” in your android studio bottom bar. And select “info” and search for “mylog”.

Converting JSON string response to class

If your API is returning a JSON string in response, then you also need to convert that JSON string response to Kotlin class. You can do that by installing a library called “Gson”. You can easily install it by adding the following line in “app/build.gradle” and running “Gradle sync”:

implementation "com.google.code.gson:gson:2.8.5"

Then create a package named “models” since it is a good practice to keep all your response classes in a separate package. Inside this package, create a file named “GeneralResponse.kt” and write the following code in it:

package com.adnantech.myapp.models

class GeneralResponse {
    lateinit var status: String
    lateinit var message: String
}

When the response is received you simply need to do the following with the “response” string:

val generalResponse: GeneralResponse = Gson().fromJson(response, GeneralResponse::class.java)

This will convert the JSON string into your class object.

Creating an API in Node JS

We already have created a public GitHub repo that will give you a pre-built registration API. You can make the changes as per your needs. Just download the repo. Paste it anywhere on your computer. Run the following commands in the “api” folder:

> npm update
> node server.js

Make sure you have Node JS installed in your system. That’s how you can create a user registration activity in Kotlin with Node JS and Mongo DB as the backend. Check out our tutorials on Android to learn more.

3 Replies to “User registration – Kotlin, Node JS, Mongo DB”

  1. I was recommended this website by my cousin. I am not sure whether this post is written by him as no one else know such detailed about my problem.

    You’re incredible! Thanks!

Comments are closed.