Android Login Registration Using Retrofit Session Management Tutorial

android login registration using retrofit, android upload image to server using retrofit, android retrofit multipart upload image, android custom dialog with listview, android custom dialog with recyclerview

We will read Android Login Registration Using Retrofit Session Management Tutorial.

In this tutorial, we will create login and registration form in android using retrofit 2.

We will use MySQL database to store the user data.

PHP will help to store and retrieve the data from the MySQL database table.

Data transmission will be done using json and retrofit. JSON will provide data structure and retrofit will make http calls.

Retrofit Login Scenario

PHP Scripts

We will use some php files in this tutorial.

Our first php file is config.php It should contain below code lines

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

?>

Above file make connection to our database.

Second PHP script is “simpleregister.php” and it holds the following code

<?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!") );
	}
 
 ?>

This file add the new user in the database (registration) if username is unique.

Next PHP script is “simplelogin.php” with the following code lines

<?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!") );
	}
?>

Directory Files

All above three files should be in the one folder.

register and login in android, android login registration using retrofit
Directory files

 

Now go to android studio and read below to make android login register with retrofit step by step

Step 1. General Settings

First of all, make a new project in android studio.

Two general settings are there. One to add INTERNET permission and another is about dependencies.

In your AndroidManifest.xml file, copy the below line

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

This line will allow us to use internet of android device.

Add the following line in build.gradle(Module : app) file.

  implementation 'com.squareup.retrofit2:retrofit:2.5.0'
  implementation 'com.squareup.retrofit2:converter-scalars:2.5.0'

First line will write the retrofit integration in our project.

Scalar library will help us to get the JSON in string format.

Step 2. Two interfaces

For making http calls with retrofit, we need to write two interfaces.

Create a new JAVA class and give it a name like “RegisterInterface.java” and add the below code

import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;

public interface RegisterInterface {

    String REGIURL = "https://demonuts.com/Demonuts/JsonTest/Tennis/";
    @FormUrlEncoded
    @POST("simpleregister.php")
    Call<String> getUserRegi(
            @Field("name") String name,
            @Field("hobby") String hobby,
            @Field("username") String uname,
            @Field("password") String password
    );

}

We will use this interface while making the registration logic.

A string variable REGIURL contains the URL of the registration php script.

@POST(“simpleregister.php”) is having the PHP file name.

getUserRegi() method is having the URL parameters with it like name, hobby, username and password.

This interface is for registration process.

Let us make separate interface for login. So create a new JAVA class with name LoginInterface.java

import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;

public interface LoginInterface {

    String LOGINURL = "https://demonuts.com/Demonuts/JsonTest/Tennis/";
    @FormUrlEncoded
    @POST("simplelogin.php")
    Call<String> getUserLogin(

            @Field("username") String uname,
            @Field("password") String password
    );
}

Similar to registration interface, it has string variable which holds the URL and @POST annotation.

getUserLogin() method have two parameters like username and password.

Step 3. Preference Class

To maintain the Login session, we need to save current status of user (whether he is logged in or not) in shared preference.

We can also save username, hobby other information in shared preference.

To simplify this process, we need to have one separate class. So prepare a new class like PreferenceHelper.java

Source code for PreferenceHelper.java is like the below

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 will get into, name, hobby fields in the JSON response.

So I have written put and get methods for these three fields.

When the user makes successful login, server will provide us above three information. we will store them in shared preference using put methods,.

When user logged out, we will simply remove the information from shared preference or you can simple write empty string in put methods.

get methods will help us to fetch the saved information.

Step 4. Welcome Activity Works

When the user get logged in, we will redirect him to the WelcomeActivity.java 

Make a new activity with a name WelcomeActivity.

Source code lines for activity_welcome.xml is like the following

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="40sp"
        android:textColor="#000"
        android:text="Retrofit Login"/>

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

Above XML file contains three text views and one button.

First text view is having fix texts. Second and third will contain username and hobby respectively.

Button is maintaining the log out procedure.

Add the below code structure in 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();
            }
        });
    }
}

As you can see that we are filling the values like username and hobby using preference helper class.

When the user clicks the button, we will set the value of putIsLogin() as a false.

Then compiler will open the Main Activity which is working for registration process.

Step 5. Login Implementation

Create a new activity and it should have the name like LoginActivity.

In your activity_main.xml file, write down the below source code

<?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="#000"
    android:gravity="center"
    android:orientation="vertical">

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

Above XML file includes two edit texts, one button and one text view.

First two edit text will hold the value of username and password entered by the user.

When the click clicks the button, retrofit will trigger the log in web service.

A text view telling the user that if you have already registered than you can click me. When the user clicks this text view it will open registration form.

Now write down the following code block in LoginActivity.java file

import android.content.Intent;
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.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;

public class LoginActivity extends AppCompatActivity {

    private EditText etUname, etPass;
    private Button btnlogin;
    private TextView tvreg;
    private PreferenceHelper preferenceHelper;

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

        preferenceHelper = new PreferenceHelper(this);

        etUname = (EditText) findViewById(R.id.etusername);
        etPass = (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);
                LoginActivity.this.finish();
            }
        });

        btnlogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loginUser();
            }
        });
    }

    private void loginUser() {

        final String username = etUname.getText().toString().trim();
        final String password = etPass.getText().toString().trim();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(LoginInterface.LOGINURL)
                .addConverterFactory(ScalarsConverterFactory.create())
                .build();

        LoginInterface api = retrofit.create(LoginInterface.class);

        Call<String> call = api.getUserLogin(username,password);

        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Log.i("Responsestring", response.body().toString());
                //Toast.makeText()
                if (response.isSuccessful()) {
                    if (response.body() != null) {
                        Log.i("onSuccess", response.body().toString());

                        String jsonresponse = response.body().toString();
                        parseLoginData(jsonresponse);

                    } else {
                        Log.i("onEmptyResponse", "Returned empty response");//Toast.makeText(getContext(),"Nothing returned",Toast.LENGTH_LONG).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {

            }
        });

    }

    private void parseLoginData(String response){
        try {
            JSONObject jsonObject = new JSONObject(response);
            if (jsonObject.getString("status").equals("true")) {

                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();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    private void saveInfo(String response){

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

                    JSONObject dataobj = dataArray.getJSONObject(i);
                    preferenceHelper.putName(dataobj.getString("name"));
                    preferenceHelper.putHobby(dataobj.getString("hobby"));
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

}

Now let us check the above code step by step.

Consider the below code

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

        btnlogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loginUser();
            }
        });

When the user clicks the text view, compiler will open the main activity which is working as the registration form.

Click on the log in button will call the loginUser() method.

Inside loginUser() method, compiler will first fetch the value of username and password from two edit texts into the string variables.

After this, it will create the object of Retrofit class. Here, .baseUrl(Logininterface.LOGINURL) line is integrating the login URL.

api.getUserLogin(username,password) will make the http call to the web server using retrofit.

When the server gives the JSON response, compiler will call onResponse() method.

Inside onResponse() method, compiler will execute the parseLoginData() method.

Now compiler will first check the “status” field of the JSON response. If it’s value is “true” then compiler will call the saveInfo() method.

Now compiler will move into saveInfo() method. Here, it save some information in shared preference using preference helper class.

After this, compiler will again move into parseLoginData() method and then it will open the welcome activity.

Step 6. Main Works (Registration)

In your activity_main.xml file, add the following code lines

<?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="#000">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:gravity="center"
        android:layout_marginTop="10dp"
        android:textColor="#fff"
        android:textSize="29sp"
        android:text="Retrofit Register"/>

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

Four edit texts, one button and one text view is present in above file.

Now in MainActivity.java file, write down the below lines

import android.content.Intent;
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.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;

public class MainActivity extends AppCompatActivity {

    private EditText etname, ethobby, etusername, etpassword;
    private Button btnregister;
    private TextView tvlogin;
    private PreferenceHelper preferenceHelper;

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

        preferenceHelper = new PreferenceHelper(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);
                MainActivity.this.finish();
            }
        });

        btnregister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                registerMe();
            }
        });

    }

    private void registerMe() {

        final String name = etname.getText().toString();
        final String hobby = ethobby.getText().toString();
        final String username = etusername.getText().toString();
        final String password = etpassword.getText().toString();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(RegisterInterface.REGIURL)
                .addConverterFactory(ScalarsConverterFactory.create())
                .build();

        RegisterInterface api = retrofit.create(RegisterInterface.class);

        Call<String> call = api.getUserRegi(name,hobby,username,password);

        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Log.i("Responsestring", response.body().toString());
                //Toast.makeText()
                if (response.isSuccessful()) {
                    if (response.body() != null) {
                        Log.i("onSuccess", response.body().toString());

                        String jsonresponse = response.body().toString();
                        try {
                            parseRegData(jsonresponse);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    } else {
                        Log.i("onEmptyResponse", "Returned empty response");//Toast.makeText(getContext(),"Nothing returned",Toast.LENGTH_LONG).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {

            }
        });
    }

    private void parseRegData(String response) throws JSONException {

        JSONObject jsonObject = new JSONObject(response);
        if (jsonObject.optString("status").equals("true")){

            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, jsonObject.getString("message"), Toast.LENGTH_SHORT).show();
        }
    }

    private void saveInfo(String response){

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

                    JSONObject dataobj = dataArray.getJSONObject(i);
                    preferenceHelper.putName(dataobj.getString("name"));
                    preferenceHelper.putHobby(dataobj.getString("hobby"));
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

Here, compiler will first check if user is already logged in or not?

If user is logged in than it will open the Welcome activity. If not then, compiler will find UI views using findViewById() method.

If user clicks the text view than it will open the Login Activity.

When the user clicks the button, compiler will execute registerMe() method.

Inside registerMe() method, compiler will get the values like name, hobby, username and password from the edit texts into string variables.

Then using these string variables, it will make the http call for registration.

When the server gives the JSON response, it will call the parseRegData() method.

Inside  parseRegData() method, if “status” from JSON response is true then compiler will call saveInfo() method. Inside this method, it will save required information in shared preferences.

Then it will go back to  parseRegData() method and then it will open the Welcome activity.

Download Code for android login registration using retrofit

Github Link to source code of this example