Android networking library allows android applications to connect to online services and also run asynchronous network requests
Android networking library is one of the fast and easy methods that allow android apps to connect to online servers and process data and give responses to the user
In this article, we shall discuss how you can log in to an android app using a networking library and connect to a REST API that will process data in the online server
Android networking library is available freely in GitHub view the documentation on this link https://github.com/amitshekhariitbhu/Fast-Android-Networking
To begin;
- Create and set up your project in android studio
- By default, two files will be created activity_main.xml and MainActivity.kt
- In xml file, add the username and password fields and also the login button
You can use the below code and paste it in your xml file
<?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">
<LinearLayout
android:layout_marginTop="200dp"
android:layout_marginStart="100dp"
android:layout_marginEnd="100dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fill Details to Login"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Username"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="@+id/username"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:text="Login"
android:id="@+id/loginbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
- Since the application will need to connect to online server, we will need to add the internet permission in the manifest file
<uses-permission android:name="android.permission.INTERNET" />
The full manifest file is as follows
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.loginproject">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.LoginProject">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
- We need to import the android networking library in our project from GitHub.
In the build.gradle file for app, implement the library by adding the following line of code in the dependencies section
implementation 'com.amitshekhar.android:android-networking:1.0.2'
The full build.gradle file for app is as follows
plugins {
id 'com.android.application'
id 'kotlin-android'
}
android {
compileSdkVersion 31
buildToolsVersion "30.0.2"
defaultConfig {
applicationId "com.example.loginproject"
minSdkVersion 22
targetSdkVersion 31
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.7.0'
implementation 'androidx.appcompat:appcompat:1.4.0'
implementation 'com.google.android.material:material:1.4.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.2'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
implementation 'com.amitshekhar.android:android-networking:1.0.2'
}
Having imported the networking library, you will need to implement it in MainActivity.kt
The below code shows how the android networking library is used
AndroidNetworking.post("https://www.solutionspacenet.com/apis/login")
.addBodyParameter("username",username)
.addBodyParameter("password",password)
.build()
.getAsJSONObject(object :JSONObjectRequestListener{
override fun onResponse(response: JSONObject?) {
if (response!!.getInt(STATUS) == 200) {
Toast.makeText(applicationContext,"Login successful",Toast.LENGTH_LONG).show()
val intent = Intent(applicationContext,MainActivity::class.java)
val userData = Gson().fromJson<LoginModel>(response.getJSONObject("data").toString(),LoginModel::class.java)
startActivity(intent)
finish()
} else {
Toast.makeText(applicationContext,"error",Toast.LENGTH_LONG).show()
}
}
override fun onError(anError: ANError?) {
}
})
The full code for MainActivity.kt is as follows
package com.example.loginproject
import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.ContactsContract.ProviderStatus.STATUS
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import com.google.android.material.snackbar.Snackbar
import org.json.JSONObject
import com.androidnetworking.AndroidNetworking
import com.androidnetworking.error.ANError
import com.androidnetworking.interfaces.JSONObjectRequestListener
import com.google.gson.Gson
import com.models.LoginModel
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var username=findViewById(R.id.username) as EditText
var password=findViewById(R.id.password) as EditText
var loginbutton=findViewById(R.id.loginbutton) as Button
loginbutton.setOnClickListener {
var next = true
if(username.toString().isEmpty()){
next = false
}
if(password.toString().isEmpty()){
next = false
}
if(next){
login(username.text.toString(),password.text.toString())
}else{
}
}
}
fun login(username:String ,password:String){
AndroidNetworking.post("https://www.solutionspacenet.com/apis/login")
.addBodyParameter("username",username)
.addBodyParameter("password",password)
.build()
.getAsJSONObject(object :JSONObjectRequestListener{
override fun onResponse(response: JSONObject?) {
if (response!!.getInt(STATUS) == 200) {
Toast.makeText(applicationContext,"Login successful",Toast.LENGTH_LONG).show()
val intent = Intent(applicationContext,MainActivity::class.java)
val userData = Gson().fromJson<LoginModel>(response.getJSONObject("data").toString(),LoginModel::class.java)
startActivity(intent)
finish()
} else {
Toast.makeText(applicationContext,"error",Toast.LENGTH_LONG).show()
}
}
override fun onError(anError: ANError?) {
}
})
}
}
- Finally, the REST API where the username and password will be sent for checking whether the combination is correct is as follows, that is login.php
<?php
header("Content-Type:application/json");
$con=mysqli_connect("localhost","database_username","database_password","database_name") or die("error"); //Replace with your database credentials
$email = $_POST["email"];
$password = $_POST["password"];
if(mysqli_num_rows(mysqli_query($con,"SELECT * FROM customers WHERE Email='$email' AND Password='$password'"))> 0){
$json = array("status" => 200,'message' => "Success");
}else{
$json = array("status" => 300,'message' => "Error");
}
echo json_encode($json);
mysqli_close($con)
?>
- Run your application and use the values you have saved in your database to login
That’s all for this simple discussion of how you can log in to android using networking library and REST API