Build an Android Application for User Login using Restful Web Services with Retrofit 2 Android Tutorial

Overview

In this tutorial We will show you how to create a simple Android app for User Login with Android Studio. This app will send the login request to the RESTFul Web Service using Retrofit 2 HTTP Client.

Follow the steps mentioned below to develop this application.

Android Application for User Login using Restful Web Services with Retrofit 2


Video Tutorials


Testing Login API with Postman

The following images show the creation of an Login API using RESTFul Webservices call in Postman

testing Login API with Postman

testing Login API with Postman failed

  • Choose request type GET and type the URL http://192.168.20.110/demo/login/test/123 (http://<server-api>/demo/login/<username_login>/<password>)
  • Click Send
  • You will see a JSON response
message == true it means user successfully login
{
 "message": "true"
}
message == false it means login failed

{
 "message": "false"
}

Create an Android Studio Project

Open Android Studio create a new project with an empty activity called LoginActivity.

Create Android Project Screen

Create Android Project Select form factor Screen

Create Android Project Choose Activity Screen

Create Android Project Finsih Screen

Project Structure

 Project Structure AndroidLoginRestfulWebserviceTutorial


Add Gradle dependencies and permission


Add the following dependencies to your build.gradle file.
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.google.code.gson:gson:2.6.1'

build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.jackrutorial.androidloginrestfulwebserviceexample"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'
    compile 'com.google.code.gson:gson:2.6.1'
}
Add the permission to access internet in the AndroidManifest.xml file.

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

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.jackrutorial.androidloginrestfulwebserviceexample">

    <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/AppTheme">
        <activity android:name=".LoginActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Define the Retrofit Interface


  • Add a new package to src/main/java with the name com.jackrutorial.androidloginrestfulwebserviceexample.model
  • Create a ResObj class (the POJO classes are wrapped into a typed Retrofit Call class) under com.jackrutorial.androidloginrestfulwebserviceexample.model package and write the following code in it.

ResObj.java

package com.jackrutorial.androidloginrestfulwebserviceexample.model;

public class ResObj {
    private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

  • Add a new package to src/main/java with the name com.jackrutorial.androidloginrestfulwebserviceexample.remote
  • Create a UserService interface under com.jackrutorial.androidloginrestfulwebserviceexample.remote package. Define the REST API for Retrofit via the following interface.

UserService.java

package com.jackrutorial.androidloginrestfulwebserviceexample.remote;

import com.jackrutorial.androidloginrestfulwebserviceexample.model.ResObj;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;

public interface UserService {

    @GET("login/{username}/{password}")
    Call login(@Path("username") String username, @Path("password") String password);
}

In the above class, we’ve defined GET method that perform HTTP requests with annotation.

Create a RetrofitClient class under com.jackrutorial.androidloginrestfulwebserviceexample.remote package and write the following code in it.

RetrofitClient.java

package com.jackrutorial.androidloginrestfulwebserviceexample.remote;

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitClient {

    private static Retrofit retrofit = null;

    public static Retrofit getClient(String url){
        if(retrofit == null){
            retrofit = new Retrofit.Builder()
                    .baseUrl(url)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}

Create a ApiUtils class under com.jackrutorial.androidloginrestfulwebserviceexample.remote package and write the following code in it.

ApiUtils.java

package com.jackrutorial.androidloginrestfulwebserviceexample.remote;

public class ApiUtils {

    public static final String BASE_URL = "http://192.168.20.110/demo/";

    public static UserService getUserService(){
        return RetrofitClient.getClient(BASE_URL).create(UserService.class);
    }
}

Adjust activity


Change the activity_login.xml layout to the following.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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="com.jackrutorial.androidloginrestfulwebserviceexample.LoginActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Login"
            android:textAppearance="?android:attr/textAppearanceLarge"
            />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Username: "
            />

        <EditText
            android:id="@+id/edtUsername"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Password: "
            />

        <EditText
            android:id="@+id/edtPassword"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPassword"
            />

        <Button
            android:id="@+id/btnLogin"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Login"
            />

    </LinearLayout>

</android.support.constraint.ConstraintLayout>

Change LoginActivity activity code to the following.

package com.jackrutorial.androidloginrestfulwebserviceexample;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.jackrutorial.androidloginrestfulwebserviceexample.model.ResObj;
import com.jackrutorial.androidloginrestfulwebserviceexample.remote.ApiUtils;
import com.jackrutorial.androidloginrestfulwebserviceexample.remote.UserService;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LoginActivity extends AppCompatActivity {

    EditText edtUsername;
    EditText edtPassword;
    Button btnLogin;
    UserService userService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        edtUsername = (EditText) findViewById(R.id.edtUsername);
        edtPassword = (EditText) findViewById(R.id.edtPassword);
        btnLogin = (Button) findViewById(R.id.btnLogin);
        userService = ApiUtils.getUserService();

        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = edtUsername.getText().toString();
                String password = edtPassword.getText().toString();
                //validate form
                if(validateLogin(username, password)){
                    //do login
                    doLogin(username, password);
                }
            }
        });

    }

    private boolean validateLogin(String username, String password){
        if(username == null || username.trim().length() == 0){
            Toast.makeText(this, "Username is required", Toast.LENGTH_SHORT).show();
            return false;
        }
        if(password == null || password.trim().length() == 0){
            Toast.makeText(this, "Password is required", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    private void doLogin(final String username,final String password){
        Call call = userService.login(username,password);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                if(response.isSuccessful()){
                    ResObj resObj = response.body();
                    if(resObj.getMessage().equals("true")){
                        //login start main activity
                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        intent.putExtra("username", username);
                        startActivity(intent);

                    } else {
                        Toast.makeText(LoginActivity.this, "The username or password is incorrect", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(LoginActivity.this, "Error! Please try again!", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call call, Throwable t) {
                Toast.makeText(LoginActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}

Create Activity

  • Click the app folder for your project and choose File > New > Activity > Empty Activity
  • Name the new activity "MainActivity".
  • Click Finish.
Change the activity_main.xml layout to the following.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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="com.jackrutorial.androidloginrestfulwebserviceexample.MainActivity">

    <TextView
        android:id="@+id/txtUsername"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        />

</android.support.constraint.ConstraintLayout>

Change MainActivity activity code to the following.

package com.jackrutorial.androidloginrestfulwebserviceexample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    TextView txtUsername;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txtUsername = (TextView) findViewById(R.id.txtUsername);

        Bundle extras = getIntent().getExtras();
        String username;

        if(extras != null){
            username = extras.getString("username");
            txtUsername.setText("Welcome " + username);
        }

    }
}

Run this app in the Android Emulator


You can run this app from an Android Studio project. Or you can run this app that's been installed on the emulator as you would run any app on a device.
To start the emulator and run this app in your project
  • Open Android Studio project and click Run.
  • In the Select Deployment Target dialog, select an existing emulator definition, and then click OK.
Note: 
  • If you don’t see a definition you want to use, click Create New Virtual Device to launch the AVD Manager. After you define a new AVD, in the Select Deployment Target dialog, click OK.
  • If you want to use this emulator definition as the default for your project, select Use same selection for future launches.
android login screen

android welcome screen

Required

Previous Post
Next Post

post written by: