android login, android rest api example, android login with online authentication, android login using PHP and MySQL, How to Login in Android using a Rest API

How to Login in Android using a Rest API

Unlike before wherein android we could have either the login credentials that is the username hand-coded in the application and the user given the correct credentials or saving the credentials in a local database called SQLite, these days android applications act as a submodule for web applications whereby data stored in the online web server is used in android applications.

Users are either given options either to use a web application or an android app and achieve the same purpose, therefore data must be in real-time while accessing either the web or android app.

In this article, we shall cover how to login in android using a Rest API whereby we will need an online server to validate the username and login and then depending on the result given by the rest API redirect the user.

Previously, we have discussed how to create a simple login application in android whereby we have shown you how to create text views, edit text and buttons for inputting data to the android app and we also shown how to collect the data from the XML file to the Main Activity file. Also, we discussed how to create a REST API in PHP and also how to test the API using postman.

For this article, we shall go direct to connecting the android app with the Rest API and show how to send and receive data to the server using Async task method in android

For easier reference, the code below is for the xml file that has the login screen design

<?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">

 

    <?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"

        xmlns:tools="http://schemas.android.com/tools"

        android:background="#9cc2e5"

        tools:context=".MainActivity">

        <ImageView

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:layout_marginLeft="150dp"

            android:layout_marginTop="50dp"

            android:id="@+id/imagelogo"

            android:src="@mipmap/ic_launcher"

            />

        <TextView

            android:layout_width="match_parent"

            android:layout_height="wrap_content"

            android:text="Username"

            android:layout_below="@+id/imagelogo"

            android:textSize="40dp"

            android:layout_marginTop="50dp"

            android:id="@+id/usernameview"

            />

        <EditText

            android:layout_width="match_parent"

            android:layout_height="wrap_content"

            android:layout_below="@+id/usernameview"

            android:id="@+id/username"

            />

        <TextView

            android:layout_width="match_parent"

            android:layout_height="wrap_content"

            android:text="Password"

            android:layout_below="@+id/username"

            android:textSize="40dp"

            android:layout_marginTop="20dp"

            android:id="@+id/passwordview"

            />

        <EditText

            android:layout_width="match_parent"

            android:layout_height="wrap_content"

            android:layout_below="@+id/passwordview"

            android:id="@+id/password"

            android:inputType="textPassword"

            />

        <Button

            android:layout_width="300dp"

            android:layout_height="80dp"

            android:text="Login"

            android:id="@+id/login"

            android:layout_marginLeft="50dp"

            android:layout_below="@+id/password"

            />

    </RelativeLayout>

 

</androidx.constraintlayout.widget.ConstraintLayout>

While this code shows how to collect the details from the xml file in the java file

  EditText username,password;

    Button login;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        username=(EditText)findViewById(R.id.username);

        password=(EditText)findViewById(R.id.password);

        login=(Button) findViewById(R.id.login);

        login.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View view) {

                if(username.getText().toString().equals("")){

                    Toast.makeText(getApplicationContext(), "Username cannot be blank", Toast.LENGTH_SHORT).show();

                }else if(password.getText().toString().equals("")){

                    Toast.makeText(getApplicationContext(), "password cannot be blank", Toast.LENGTH_SHORT).show();

                }else{

                    Toast.makeText(getApplicationContext(), "login method to proceed", Toast.LENGTH_SHORT).show();

                }

            }

        });

    }

This code below is the REST API code developed using PHP and MySQL that will process the data sent by the android code

<?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)

?>

Next, in the manifest file, add the internet permission that will allow the application to send and access data from online server

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

The full manifest file code is as below

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.example.firstandroidapp">

<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.FirstAndroidApp">

        <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>

Next, we are now going to add the code that collects the username and password using the async task method

  • First, define the method that will be called when the login button is clicked, for example for this tutorial, the method used is Login().

login.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View view) {

                if(username.equals("")){

                    Toast.makeText(getApplicationContext(), "Username cannot be blank", Toast.LENGTH_SHORT).show();

                }else if(password.equals("")){

                    Toast.makeText(getApplicationContext(), "password cannot be blank", Toast.LENGTH_SHORT).show();

                }else{

                    Login lg = new Login(MainActivity.this);

                    lg.execute();

                }

            }

        });

  • After closing the onCreate method, you will now need to implement the Login method and make sure it extends the AsyncTask so that it can use its properties
  • The AsyncTask has different parts and performs its activity in a synchronous order, that is one at a time

It has a pre execute method that alerts the user that the process has started. At this point, the progress bar is usually displayed to make the user stick in that position and wait for the result

The do in background method where you define the URL where you want the variables, that is username and password be sent and also you open the HTTP connection

The on progress method does not do a lot other than to update the progress of the request

The on post execute method returns the result and at this point is where the decisions are made.

The code below shows the full java code with complete login using REST API and async task method

package com.example.firstandroidapp;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;

import android.app.ProgressDialog;

import android.content.Context;

import android.content.Intent;

import android.os.AsyncTask;

import android.os.Bundle;

import android.net.ConnectivityManager;

import android.net.NetworkInfo;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Toast;

 

import org.json.JSONArray;

import org.json.JSONException;

import org.json.JSONObject;

 

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.OutputStream;

import java.io.OutputStreamWriter;

import java.net.HttpURLConnection;

import java.net.MalformedURLException;

import java.net.URL;

import java.net.URLEncoder;

 

public class MainActivity extends AppCompatActivity {

    EditText usernametext,passwordtext;

    Button login;

    String username,password;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        usernametext=(EditText)findViewById(R.id.username);

        passwordtext=(EditText)findViewById(R.id.password);

        login=(Button) findViewById(R.id.login);

 

         username= usernametext.getText().toString();

         password= passwordtext.getText().toString();

        login.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View view) {

                if(username.equals("")){

                    Toast.makeText(getApplicationContext(), "Username cannot be blank", Toast.LENGTH_SHORT).show();

                }else if(password.equals("")){

                    Toast.makeText(getApplicationContext(), "password cannot be blank", Toast.LENGTH_SHORT).show();

                }else{

                    Login lg = new Login(MainActivity.this);

                    lg.execute();

                }

            }

        });

    }

 

    class Login extends AsyncTask<String, Void, String> {

        AlertDialog alertDialog;

        Context context;

        int msg;

 

        ProgressDialog progressDialog;

        Login(Context ctx) {

            this.context = ctx;

        }

 

        @Override

        protected void onPreExecute() {

            progressDialog = ProgressDialog.show(context, "", "Logging you in...... Please wait");

 

        }

 

        @Override

        protected String doInBackground(String... params) {

 

            String login_url ="https://www.solutionspacenet.com/apis/login";

            try {

                URL url = new URL(login_url);

                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

                httpURLConnection.setConnectTimeout(10000);

                httpURLConnection.setRequestMethod("POST");

                httpURLConnection.setDoOutput(true);

                httpURLConnection.setDoInput(true);

                OutputStream OS = httpURLConnection.getOutputStream();

                BufferedWriter bufferedWriter = new BufferedWriter(

                        new OutputStreamWriter(OS, "UTF-8"));

                String data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8") + "&"

                        + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");

                bufferedWriter.write(data);

                bufferedWriter.flush();

                bufferedWriter.close();

                OS.close();

                InputStream inputStream = httpURLConnection.getInputStream();

                BufferedReader bufferedReader = new BufferedReader(

                        new InputStreamReader(inputStream, "iso-8859-1"));

                String response = "";

                String line = "";

                while ((line = bufferedReader.readLine()) != null) {

                    response += line;

                }

                bufferedReader.close();

                inputStream.close();

                httpURLConnection.disconnect();

 

                try {

                    JSONArray jsonarray = new JSONArray(response);

                    for (int i = 0; i < jsonarray.length(); i++) {

                        JSONObject jsonobject = jsonarray.getJSONObject(i);

                        msg = jsonobject.getInt("status");

                    }

                } catch (JSONException e) {

                    e.printStackTrace();

                    return response;

                }

                return "good";

            } catch (MalformedURLException e) {

                e.printStackTrace();

                return "fail";

            } catch (IOException ee) {

                ee.printStackTrace();

                return "fail";

            }

 

        }

 

        @Override

        protected void onProgressUpdate(Void... values) {

 

            super.onProgressUpdate(values);

        }

 

        @Override

        protected void onPostExecute(String result) {

            progressDialog.dismiss();

            if (result.equals("fail")) {

                progressDialog.dismiss();

            } else if (msg == 200) {

                usernametext.setText("");

                passwordtext.setText("");

                progressDialog.dismiss();

                Toast.makeText(context, "Login successful", Toast.LENGTH_SHORT).show();

            } else if (msg == 0) {

                progressDialog.dismiss();

                Toast.makeText(context, "Login Failed", Toast.LENGTH_LONG).show();

            }

 

        }

 

    }

}

 

When you save and execute this code in a real or test device, you will see the actual logging happening from your device.

Please note that you should replace the URL we have sued in this article with an actual URL in your server so that the credentials you use can work. In case of any inquiries, let us know through our support email