Android Login And Registration Example With PHP MySQL Session Management

android login and registration

Hello, geeks. Welcome to Android login and Registration example.

I have found many tutorials covering Android login and Registration, but there are few issues. Some tutorial covers only registration part. Some may cover only login part.

If there is any example which covers both Android login and Registration, then it is not maintaining login session.

Maintaining login session is the most important part of whole professional login scenario.

So I decided to cover all below scenarios.

  1. Register user and upload his information to the server using PHP and MySQL.
  2. Login user and maintain session until he clicks on logout button.

So at the end of the register and login in Android example, you will get all the things needed for maintaining professional login session.

You will also get the professional format to call remote Web Services in proper and easiest way at the end of Android login and Registration example.

You may find this tutorial little lengthy but once you give it 10 minutes, you will be able to call all web services easily in all your future apps.

First, check the output of Android login and Registration tutorial, then we will create it.

Layout Previews

register and login in Android
Register Screen
register and login in Android
Login Screen

Wait for a second

We will use JSON Parsing in this tutorial.

If you don’t know how to parse JSON, then check JSON Parsing In Android tutorial first.

Download Source Code for Android login and Registration

[sociallocker] Download Code [/sociallocker]

Creating Android login and Registration Tutorial step by step

Step 1: Creating a PHP file for registration

Create a new PHP file named “config.php” and add below

<?php
$host="localhost";
$user="your username";
$password="your password";
$db = "your db name";

$con = mysqli_connect($host,$user,$password,$db);

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }else{  //echo "Connect"; 
  
   
   }

?>

Create a new PHP file and name it “simpleregister.php”

Add below code in it

<?php

   if($_SERVER['REQUEST_METHOD']=='POST'){
  // echo $_SERVER["DOCUMENT_ROOT"];  // /home1/demonuts/public_html
//including the database connection file
       include_once("config.php");
       
        $name = $_POST['name'];
 	$username = $_POST['username'];
 	$password = $_POST['password'];
 	$hobby= $_POST['hobby'];
  
	 if($name == '' || $username == '' || $password == '' || $hobby == ''){
	        echo json_encode(array( "status" => "false","message" => "Parameter missing!") );
	 }else{
			 
	        $query= "SELECT * FROM registerDemo WHERE username='$username'";
	        $result= mysqli_query($con, $query);
		 
	        if(mysqli_num_rows($result) > 0){  
	           echo json_encode(array( "status" => "false","message" => "Username already exist!") );
	        }else{ 
		 	 $query = "INSERT INTO registerDemo (name,hobby,username,password) VALUES ('$name','$hobby','$username','$password')";
			 if(mysqli_query($con,$query)){
			    
			     $query= "SELECT * FROM registerDemo WHERE username='$username'";
	                     $result= mysqli_query($con, $query);
		             $emparray = array();
	                     if(mysqli_num_rows($result) > 0){  
	                     while ($row = mysqli_fetch_assoc($result)) {
                                     $emparray[] = $row;
                                   }
	                     }
			    echo json_encode(array( "status" => "true","message" => "Successfully registered!" , "data" => $emparray) );
		 	 }else{
		 		 echo json_encode(array( "status" => "false","message" => "Error occured, please try again!") );
		 	}
	    }
	            mysqli_close($con);
	 }
     } else{
			echo json_encode(array( "status" => "false","message" => "Error occured, please try again!") );
	}
 
 ?>

Step 2: Creating a PHP file for login

Create a new PHP file and name it “simplelogin.php”

Add below code in it

<?php

   if($_SERVER['REQUEST_METHOD']=='POST'){
  // echo $_SERVER["DOCUMENT_ROOT"];  // /home1/demonuts/public_html
//including the database connection file
       include_once("config.php");
       
        $username = $_POST['username'];
 	$password = $_POST['password'];
 	
	 if( $username == '' || $password == '' ){
	        echo json_encode(array( "status" => "false","message" => "Parameter missing!") );
	 }else{
	 	$query= "SELECT * FROM registerDemo WHERE username='$username' AND password='$password'";
	        $result= mysqli_query($con, $query);
		 
	        if(mysqli_num_rows($result) > 0){  
	         $query= "SELECT * FROM registerDemo WHERE username='$username' AND password='$password'";
	                     $result= mysqli_query($con, $query);
		             $emparray = array();
	                     if(mysqli_num_rows($result) > 0){  
	                     while ($row = mysqli_fetch_assoc($result)) {
                                     $emparray[] = $row;
                                   }
	                     }
	           echo json_encode(array( "status" => "true","message" => "Login successfully!", "data" => $emparray) );
	        }else{ 
	        	echo json_encode(array( "status" => "false","message" => "Invalid username or password!") );
	        }
	         mysqli_close($con);
	 }
	} else{
			echo json_encode(array( "status" => "false","message" => "Error occured, please try again!") );
	}
?>

PHP Directory

Make sure that all three PHP files are in the same folder.

My all files are in the “Tennis” folder as below image.

register and login in android
Directory

PHP part is over. Now come to Android Studio and create a new project.

Step 3: Updating AndroidManifest.xml file

 add required permissions between <manifest>ā€¦.</manifest> tag.
 <uses-permission android:name="android.permission.INTERNET" />
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Note: If you are targeting SDK version above 22 (Above Lollipop)  then you need to ask a user for granting runtime permissions. Check marshmallow runtime permission for more information.

Final code for AndroidManifest.xml file

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

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

Step 4: Adding common classes into project

We will add common classes which contain public constant variables and public methods.

We can use these variables and methods anywhere in the project so that it will reduce data redundancy.

That means we will write them only once and then we will use them anytime and anywhere when needed.

Names of the classes are:

  1. PreferenceHelper
  2. AndyConstants
  3. AndyUtils
  4. HttpRequest
  5. ParseContent

Step 5: Making PreferenceHelper

Create a new Java class and add below code

import android.content.Context;
import android.content.SharedPreferences;

public class PreferenceHelper {

    private final String INTRO = "intro";
    private final String NAME = "name";
    private final String HOBBY = "hobby";
    private SharedPreferences app_prefs;
    private Context context;

    public PreferenceHelper(Context context) {
        app_prefs = context.getSharedPreferences("shared",
                Context.MODE_PRIVATE);
        this.context = context;
    }

    public void putIsLogin(boolean loginorout) {
        SharedPreferences.Editor edit = app_prefs.edit();
        edit.putBoolean(INTRO, loginorout);
        edit.commit();
    }
    public boolean getIsLogin() {
        return app_prefs.getBoolean(INTRO, false);
    }

    public void putName(String loginorout) {
        SharedPreferences.Editor edit = app_prefs.edit();
        edit.putString(NAME, loginorout);
        edit.commit();
    }
    public String getName() {
        return app_prefs.getString(NAME, "");
    }

    public void putHobby(String loginorout) {
        SharedPreferences.Editor edit = app_prefs.edit();
        edit.putString(HOBBY, loginorout);
        edit.commit();
    }
    public String getHobby() {
        return app_prefs.getString(HOBBY, "");
    }

 }

We use this class to save some information (name, hobby, a user is login or logout?, etc.) in SharedPreferences.

All methods starting with put is used to save information.

All methods starting with get is used to get saved information.

Step 6: Creating AndyConstants

Create a new Java class and copy following source code

public class AndyConstants {
    // web service url constants
    public class ServiceType {
          public static final String BASE_URL = "http://demonuts.com/Demonuts/JsonTest/Tennis/";
        public static final String LOGIN = BASE_URL + "simplelogin.php";
        public static final String REGISTER =  BASE_URL + "simpleregister.php";

   }
    // webservice key constants
    public class Params {

        public static final String NAME = "name";
        public static final String HOBBY = "hobby";
        public static final String USERNAME = "username";
        public static final String PASSWORD = "password";
       }
}

AndyConstants class contain URL constants and Parameter constants.

Step 7: Preparing AndyUtils

Create a Java class named AndyUtils and add following source code

import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class AndyUtils {
  
    private static ProgressDialog mProgressDialog;
    public static void showSimpleProgressDialog(Context context, String title,String msg, boolean isCancelable) {
        try {
            if (mProgressDialog == null) {
                mProgressDialog = ProgressDialog.show(context, title, msg);
                mProgressDialog.setCancelable(isCancelable);
            }
            if (!mProgressDialog.isShowing()) {
                mProgressDialog.show();
            }

        } catch (IllegalArgumentException ie) {
            ie.printStackTrace();
        } catch (RuntimeException re) {
            re.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void showSimpleProgressDialog(Context context) {
        showSimpleProgressDialog(context, null, "Loading...", false);
    }
    public static void removeSimpleProgressDialog() {
        try {
            if (mProgressDialog != null) {
                if (mProgressDialog.isShowing()) {
                    mProgressDialog.dismiss();
                    mProgressDialog = null;
                }
            }
        } catch (IllegalArgumentException ie) {
            ie.printStackTrace();

        } catch (RuntimeException re) {
            re.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity == null) {
            return false;
        } else {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

}

This class contains a methods to show(showSimplrProgressDialog()) and remove(removeSimpleProgressDialog()) progress dialog when app is fetching JSON data from server.

AndyUtils also includes a method (isNetworkAvailable()) to check whether the Internet of Android device is on or off.

Step 8: Preparing HttpRequest Class

Make new Java class named HttpRequest and add following source code

import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
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.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * Since HttpClient,BasicNameValuePairs, etc...  are deprecated.
 * I've searched for a good alternative, and couldn't find any. Eventually ended up writing my own solution, so I decided to share to those who needs it.
 * Main goals: to make it intuitive, short, clean and reasonable.
 * NOTE methods: .prepare(), preparePost(), withData(map) & withData(string) are build to allow caller to chain in different variations, examples:
 *HttpRequest req=new HttpRequest("http://host:port/path");
 *
 *Example 1: //prepare Http Post request and send to "http://host:port/path" with data params name=Bubu and age=29, return true - if worked
 *req.preparePost().withData("name=Bubu&age=29").send();
 *
 *Example 2: //prepare http get request,  send to "http://host:port/path" and read server's response as String
 *req.prepare().sendAndReadString();
 *
 *Example 3: //prepare Http Post request and send to "http://host:port/path" with name=Bubu and age=29 and read server's response as JSONObject
 *HashMap<String, String>params=new HashMap<>();
 params.put("name", "Groot");
 params.put("age", "29");
 *req.preparePost().withData(params).sendAndReadJSON();
 */
public class HttpRequest {
    //Supported HttpRequest methods
    public static enum Method{
        POST,PUT,DELETE,GET;
    }
    private URL url;
    private HttpURLConnection con;
    private OutputStream os;
    //After instantiation, when opening connection - IOException can occur
    public HttpRequest(URL url)throws IOException{
        this.url=url;
        con = (HttpURLConnection)this.url.openConnection();
    }
    //Can be instantiated with String representation of url, force caller to check for IOException which can be thrown
    public HttpRequest(String url)throws IOException{
        this(new URL(url));
        Log.d("parameters", url);
    }

    /**
     * Sending connection and opening an output stream to server by pre-defined instance variable url
     *
     * @param //isPost boolean - indicates whether this request should be sent in POST method
     * @throws IOException - should be checked by caller
     * */
    private void prepareAll(Method method)throws IOException{
        con.setDoInput(true);
        con.setRequestMethod(method.name());
        if(method== Method.POST||method== Method.PUT){
            con.setDoOutput(true);
            os = con.getOutputStream();
        }
    }
    //prepare request in GET method
    //@return HttpRequest this instance -> for chaining method @see line 22
    public HttpRequest prepare() throws IOException{
        prepareAll(Method.GET);
        return this;
    }
    /**
     * Prepares HttpRequest method with for given method, possible values: HttpRequest.Method.POST,
     * HttpRequest.Method.PUT, HttpRequest.Method.GET & HttpRequest.Method.DELETE
     *
     * @param method HttpRequest.Method - nested enum HttpRequest.Method constant
     * @return HttpRequest this instance -> for chaining method @see line 22
     * @throws IOException - should be checked by caller
     * */
    public HttpRequest prepare(HttpRequest.Method method)throws IOException{
        prepareAll(method);
        return this;
    }
    /**
     * Adding request headers (standard format "Key":"Value")
     *
     * @param headers String variadic params in standard format "Key":"Value"
     * @return HttpRequest this instance -> for chaining method @see line 22
     * */
    public HttpRequest withHeaders(String... headers){
        for(int i=0,last=headers.length;i<last;i++) {
            String[]h=headers[i].split("[:]");
            con.setRequestProperty(h[0],h[1]);
        }
        return this;
    }

    /**
     * Writes query to open stream to server
     *
     * @param query String params in format of key1=v1&key2=v2 to open stream to server
     * @return HttpRequest this instance -> for chaining method @see line 22
     * @throws IOException - should be checked by caller
     * */
    public HttpRequest withData(String query) throws IOException{
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        writer.write(query);
        writer.close();
        return this;
    }
    /**
     * Builds query on format of key1=v1&key2=v2 from given hashMap structure
     * for map: {name=Bubu, age=29} -> builds "name=Bubu&age=29"
     * for map: {Iam=Groot} -> builds "Iam=Groot"
     *
     * @param params HashMap consists of key-> value pairs to build query from
     * @return HttpRequest this instance -> for chaining method @see line 22
     * @throws IOException - should be checked by caller
     * */
    public HttpRequest withData(HashMap<String,String> params) throws IOException{
        StringBuilder result=new StringBuilder();
        for(Map.Entry<String,String>entry : params.entrySet()){
            result.append((result.length()>0?"&":"")+entry.getKey()+"="+entry.getValue());//appends: key=value (for first param) OR &key=value(second and more)
            Log.d("parameters",entry.getKey()+"  ===>  "+ entry.getValue());
        }
        withData(result.toString());
         return this;
    }
    //When caller only need to send, and don't need String response from server
    public int send() throws IOException{
        return con.getResponseCode(); //return HTTP status code to indicate whether it successfully sent
    }
    /**
     * Sending request to the server and pass to caller String as it received in response from server
     *
     * @return String printed from server's response
     * @throws IOException - should be checked by caller
     * */
    public String sendAndReadString() throws IOException{
        BufferedReader br=new BufferedReader(new InputStreamReader(con.getInputStream()));
        StringBuilder response=new StringBuilder();
        for(String line;(line=br.readLine())!=null;)response.append(line+"\n");
        Log.d("ressss",response.toString());
        return response.toString();
     }
    /**
     * Sending request to the server and pass to caller its raw contents in bytes as it received from server.
     *
     * @return byte[] from server's response
     * @throws IOException - should be checked by caller
     * */
    public byte[] sendAndReadBytes() throws IOException{
        byte[] buffer = new byte[8192];
        InputStream is = con.getInputStream();
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        for (int bytesRead;(bytesRead=is.read(buffer))>=0;)output.write(buffer, 0, bytesRead);
        return output.toByteArray();
    }
    //JSONObject representation of String response from server
    public JSONObject sendAndReadJSON() throws JSONException, IOException{
        return new JSONObject(sendAndReadString());
    }
}

We use methods of this class to establish a connection between an Android device and web server.

Step 9: Creating  ParseContent

Open new Java class named ParseContent, then paste below source code

import android.app.Activity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;

public class ParseContent {

    private final String KEY_SUCCESS = "status";
    private final String KEY_MSG = "message";
    private final String KEY_AddressList = "addressList";
    private final String KEY_DATA = "Data";
    private  ArrayList<HashMap<String, String>> hashMap;
    private Activity activity;
    PreferenceHelper preferenceHelper;

    ArrayList<HashMap<String, String>> arraylist;

    public ParseContent(Activity activity) {
        this.activity = activity;
        preferenceHelper = new PreferenceHelper(activity);

    }

   public boolean isSuccess(String response) {
        try {
            JSONObject jsonObject = new JSONObject(response);
            if (jsonObject.optString(KEY_SUCCESS).equals("true")) {
                return true;
            } else {

                return false;
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return false;
    }

   public String getErrorMessage(String response) {
        try {
            JSONObject jsonObject = new JSONObject(response);
            return jsonObject.getString(KEY_MSG);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return "No data";
    }

   public void saveInfo(String response) {
       preferenceHelper.putIsLogin(true);
        try {
            JSONObject jsonObject = new JSONObject(response);
            if (jsonObject.getString(KEY_SUCCESS).equals("true")) {
              JSONArray dataArray = jsonObject.getJSONArray("data");
                for (int i = 0; i < dataArray.length(); i++) {

                   JSONObject dataobj = dataArray.getJSONObject(i);
                    preferenceHelper.putName(dataobj.getString(AndyConstants.Params.NAME));
                    preferenceHelper.putHobby(dataobj.getString(AndyConstants.Params.HOBBY));
              }
          }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
}

In above source code, isSuccess(String response)  method is used to check whether a status of response is true or false.

getErrorCode(String response) method is used to get the message of JSON data.

saveInfo(String response) method will parse JSON data. I will describe this method later.

Step 10: Creating WelcomeActivity

Create a new activity named WelcomeActivity.

Add following into activity_welcome.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    tools:context="com.exampledemo.parsaniahardik.registerloginsession.WelcomeActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:textColor="#000"
       android:id="@+id/tvname"
        android:text="Welcome"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:textColor="#000"
        android:id="@+id/tvhobby"
        android:text="Hobby"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btn"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginTop="10dp"
        android:text="Logout"/>

</LinearLayout>

Add following into WelcomeActivity.java

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.TextView;

public class WelcomeActivity extends AppCompatActivity {

    private TextView tvname,tvhobby;
    private Button btnlogout;
    private PreferenceHelper preferenceHelper;

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

        preferenceHelper = new PreferenceHelper(this);

        tvhobby = (TextView) findViewById(R.id.tvhobby);
        tvname = (TextView) findViewById(R.id.tvname);
        btnlogout = (Button) findViewById(R.id.btn);

        tvname.setText("Welcome "+preferenceHelper.getName());
        tvhobby.setText("Your hobby is "+preferenceHelper.getHobby());

        btnlogout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                preferenceHelper.putIsLogin(false);
                Intent intent = new Intent(WelcomeActivity.this,MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                WelcomeActivity.this.finish();
            }
        });

    }
}

Step 11: Preparing LoginActivity

Make a new activity named LoginActivity.

Paste below source code into activity_login.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorAccent"
    android:gravity="center"
    android:orientation="vertical"
    tools:context="com.exampledemo.parsaniahardik.registerloginsession.LoginActivity">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:id="@+id/etusername"
        android:layout_marginTop="10dp"
        android:layout_marginRight="20dp"
        android:layout_marginLeft="20dp"
        android:paddingLeft="5dp"
        android:background="#fff"
        android:hint="Enter Username" />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:id="@+id/etpassword"
        android:inputType="textPassword"
        android:layout_marginTop="10dp"
        android:layout_marginRight="20dp"
        android:layout_marginLeft="20dp"
        android:paddingLeft="5dp"
        android:background="#fff"
        android:hint="Enter Password" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btn"
        android:text="Login"
        android:background="@color/colorPrimary"
        android:textColor="#fff"
        android:layout_marginTop="10dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:id="@+id/tvreg"
        android:gravity="center"
        android:layout_marginTop="10dp"
        android:textColor="#fff"
        android:textSize="20sp"
        android:text="Guest? Register here"/>

</LinearLayout>

Source code for LoginActivity.java

import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import java.io.IOException;
import java.util.HashMap;

public class LoginActivity extends AppCompatActivity {

    private EditText etusername, etpassword;
    private Button btnlogin;
    private TextView tvreg;
    private ParseContent parseContent;
    private final int LoginTask = 1;
    private PreferenceHelper preferenceHelper;

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

        parseContent = new ParseContent(this);
        preferenceHelper = new PreferenceHelper(this);

        etusername = (EditText) findViewById(R.id.etusername);
        etpassword = (EditText) findViewById(R.id.etpassword);

        btnlogin = (Button) findViewById(R.id.btn);
        tvreg = (TextView) findViewById(R.id.tvreg);

        tvreg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(intent);
            }
        });

        btnlogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    login();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void login() throws IOException, JSONException {

        if (!AndyUtils.isNetworkAvailable(LoginActivity.this)) {
            Toast.makeText(LoginActivity.this, "Internet is required!", Toast.LENGTH_SHORT).show();
            return;
        }
        AndyUtils.showSimpleProgressDialog(LoginActivity.this);
        final HashMap<String, String> map = new HashMap<>();
        map.put(AndyConstants.Params.USERNAME, etusername.getText().toString());
        map.put(AndyConstants.Params.PASSWORD, etpassword.getText().toString());
        new AsyncTask<Void, Void, String>(){
            protected String doInBackground(Void[] params) {
                String response="";
                try {
                    HttpRequest req = new HttpRequest(AndyConstants.ServiceType.LOGIN);
                    response = req.prepare(HttpRequest.Method.POST).withData(map).sendAndReadString();
                } catch (Exception e) {
                    response=e.getMessage();
                }
                return response;
            }
            protected void onPostExecute(String result) {
                //do something with response
                Log.d("newwwss", result);
                onTaskCompleted(result,LoginTask);
            }
        }.execute();
    }

    private void onTaskCompleted(String response,int task) {
        Log.d("responsejson", response.toString());
        AndyUtils.removeSimpleProgressDialog();  //will remove progress dialog
        switch (task) {
            case LoginTask:

                if (parseContent.isSuccess(response)) {

                    parseContent.saveInfo(response);
                    Toast.makeText(LoginActivity.this, "Login Successfully!", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(LoginActivity.this,WelcomeActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                    this.finish();

                }else {
                    Toast.makeText(LoginActivity.this, parseContent.getErrorMessage(response), Toast.LENGTH_SHORT).show();
                }
        }
    }
}

Describing above class

Look at login() method

private void login() throws IOException, JSONException {
        if (!AndyUtils.isNetworkAvailable(LoginActivity.this)) {
            Toast.makeText(LoginActivity.this, "Internet is required!", Toast.LENGTH_SHORT).show();
            return;
        }
        AndyUtils.showSimpleProgressDialog(LoginActivity.this);
        final HashMap<String, String> map = new HashMap<>();
        map.put(AndyConstants.Params.USERNAME, etusername.getText().toString());
        map.put(AndyConstants.Params.PASSWORD, etpassword.getText().toString());
        new AsyncTask<Void, Void, String>(){
            protected String doInBackground(Void[] params) {
                String response="";
                try {
                    HttpRequest req = new HttpRequest(AndyConstants.ServiceType.LOGIN);
                    response = req.prepare(HttpRequest.Method.POST).withData(map).sendAndReadString();
                } catch (Exception e) {
                    response=e.getMessage();
                }
                return response;
            }
            protected void onPostExecute(String result) {
                //do something with response
                Log.d("newwwss", result);
                onTaskCompleted(result,LoginTask);
            }
        }.execute();
    }

HashMap contains parameters of Web Service. Below is HashMap.

 final HashMap<String, String> map = new HashMap<>();
        map.put(AndyConstants.Params.USERNAME, etusername.getText().toString());
        map.put(AndyConstants.Params.PASSWORD, etpassword.getText().toString());

Following source code will call web service.

 HttpRequest req = new HttpRequest(AndyConstants.ServiceType.LOGIN);
 response = req.prepare(HttpRequest.Method.POST).withData(map).sendAndReadString();

After getting JSON response in String format, onPostExecute() method is called and from it onTaskCompleted() method is called.

Below is a source code for onTaskCompleted() method.

 private void onTaskCompleted(String response,int task) {
        Log.d("responsejson", response.toString());
        AndyUtils.removeSimpleProgressDialog();  //will remove progress dialog
        switch (task) {
            case LoginTask:
                if (parseContent.isSuccess(response)) {
                    parseContent.saveInfo(response);
                    Toast.makeText(LoginActivity.this, "Login Successfully!", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(LoginActivity.this,WelcomeActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                    this.finish();
                }else {
                    Toast.makeText(LoginActivity.this, parseContent.getErrorMessage(response), Toast.LENGTH_SHORT).show();
                }
        }
    }

parseContent.saveInfo() will save information in SharedPreference.

Source code for saveInfo() method is as following

 public void saveInfo(String response) {
       preferenceHelper.putIsLogin(true);
        try {
            JSONObject jsonObject = new JSONObject(response);
            if (jsonObject.getString(KEY_SUCCESS).equals("true")) {
              JSONArray dataArray = jsonObject.getJSONArray("data");
                for (int i = 0; i < dataArray.length(); i++) {

                   JSONObject dataobj = dataArray.getJSONObject(i);
                    preferenceHelper.putName(dataobj.getString(AndyConstants.Params.NAME));
                    preferenceHelper.putHobby(dataobj.getString(AndyConstants.Params.HOBBY));
              }
          }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

Here we parse JSON Data.

JSON Data will look like below

{
    "status": "true",
    "message": "Login successfully!",
    "data": [
        {
            "id": "1",
            "name": "Hardik Parsania",
            "hobby": "Tennis",
            "username": "hardik",
            "password": "hardik"
        }
    ]
}

Look in saveInfo() method.

JSON Data starts with “{“ so it is JSONObject

We have parsed JSONObject by below

JSONObject jsonObject = new JSONObject(response);

In JSON, a key “data” starts with JSONArray “[” so it is parsed by below line

 JSONArray dataArray = jsonObject.getJSONArray("data");

hobby, name, etc. information is parsed in for” loop and it is stored using preferenceHelper as per following.

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

                   JSONObject dataobj = dataArray.getJSONObject(i);
                    preferenceHelper.putName(dataobj.getString(AndyConstants.Params.NAME));
                    preferenceHelper.putHobby(dataobj.getString(AndyConstants.Params.HOBBY));
}

Step 12: Preparing MainActivity

Add below code into activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:background="@color/colorAccent"
    tools:context="com.exampledemo.parsaniahardik.registerloginsession.MainActivity">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:id="@+id/etname"
        android:layout_marginRight="20dp"
        android:layout_marginLeft="20dp"
        android:paddingLeft="5dp"
        android:background="#fff"
        android:hint="Enter Name" />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:id="@+id/ethobby"
        android:layout_marginTop="10dp"
        android:layout_marginRight="20dp"
        android:layout_marginLeft="20dp"
        android:paddingLeft="5dp"
        android:background="#fff"
        android:hint="Enter Hobby" />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:id="@+id/etusername"
        android:layout_marginTop="10dp"
        android:layout_marginRight="20dp"
        android:layout_marginLeft="20dp"
        android:paddingLeft="5dp"
        android:background="#fff"
        android:hint="Enter Username" />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:inputType="textPassword"
        android:id="@+id/etpassword"
        android:layout_marginTop="10dp"
        android:layout_marginRight="20dp"
        android:layout_marginLeft="20dp"
        android:paddingLeft="5dp"
        android:background="#fff"
        android:hint="Enter Password" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btn"
        android:text="Register"
        android:background="@color/colorPrimary"
        android:textColor="#fff"
        android:layout_marginTop="10dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:id="@+id/tvlogin"
        android:gravity="center"
        android:layout_marginTop="10dp"
        android:textColor="#fff"
        android:textSize="20sp"
        android:text="Already Registered? Login here"/>
</LinearLayout>

Logic to register a user is written in MainActivity. So add below source code in MainActivity.java

import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import java.io.IOException;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

    private EditText etname, ethobby, etusername, etpassword;
    private Button btnregister;
    private TextView tvlogin;
    private ParseContent parseContent;
    private PreferenceHelper preferenceHelper;
    private final int RegTask = 1;

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

        preferenceHelper = new PreferenceHelper(this);
        parseContent = new ParseContent(this);

        if(preferenceHelper.getIsLogin()){
            Intent intent = new Intent(MainActivity.this,WelcomeActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            this.finish();
        }

        etname = (EditText) findViewById(R.id.etname);
        ethobby = (EditText) findViewById(R.id.ethobby);
        etusername = (EditText) findViewById(R.id.etusername);
        etpassword = (EditText) findViewById(R.id.etpassword);

        btnregister = (Button) findViewById(R.id.btn);
        tvlogin = (TextView) findViewById(R.id.tvlogin);

        tvlogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,LoginActivity.class);
                startActivity(intent);
            }
        });

        btnregister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    register();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    private void register() throws IOException, JSONException {
        if (!AndyUtils.isNetworkAvailable(MainActivity.this)) {
            Toast.makeText(MainActivity.this, "Internet is required!", Toast.LENGTH_SHORT).show();
            return;
        }
        AndyUtils.showSimpleProgressDialog(MainActivity.this);
        final HashMap<String, String> map = new HashMap<>();
        map.put(AndyConstants.Params.NAME, etname.getText().toString());
        map.put(AndyConstants.Params.HOBBY, ethobby.getText().toString());
        map.put(AndyConstants.Params.USERNAME, etusername.getText().toString());
        map.put(AndyConstants.Params.PASSWORD, etpassword.getText().toString());
        new AsyncTask<Void, Void, String>(){
            protected String doInBackground(Void[] params) {
                String response="";
                try {
                    HttpRequest req = new HttpRequest(AndyConstants.ServiceType.REGISTER);
                    response = req.prepare(HttpRequest.Method.POST).withData(map).sendAndReadString();
                } catch (Exception e) {
                    response=e.getMessage();
                }
                return response;
            }
            protected void onPostExecute(String result) {
                //do something with response
                Log.d("newwwss", result);
                onTaskCompleted(result, RegTask);
            }
        }.execute();
    }
    private void onTaskCompleted(String response,int task) {
        Log.d("responsejson", response.toString());
        AndyUtils.removeSimpleProgressDialog();  //will remove progress dialog
        switch (task) {
            case RegTask:

                if (parseContent.isSuccess(response)) {
                    parseContent.saveInfo(response);
                    Toast.makeText(MainActivity.this, "Registered Successfully!", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(MainActivity.this,WelcomeActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                    this.finish();
                }else {
                    Toast.makeText(MainActivity.this, parseContent.getErrorMessage(response), Toast.LENGTH_SHORT).show();
                }
        }
    }
}

In register() method, Web Service is called same as we did in LoginActivity.

Just URL of service and parameters are different.

So finally after doing all above stuff, now you have a complete professional format to make an international Android app.

If you follow this professional format, not only register and login but you can call all other web services very easily.

That’s all for Android login and Registration example.

Feel free to put your queries and reviews in the comment section. Thank you šŸ™‚