Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Login and Registration Form in Android

Login and Registration Form in Android

Hi Developer, In this tutorial we will discuss how to create Login and Registration Form in Android. This is required for any app, where the user is required to register and then login to his account. This tutorial is second part of Android Login and Registration with PHP MySQL Tutorial. So before continuing, make sure that you have a server up and running on your localhost and you have created the PHP API, that will handle Login and Registration data from the android app.

Once you have a server running and all the API’s set up, let’s get started to create Login and Registration Form in Android, We will be having three screens in our app as shown in the figure below.

Login and Registration Form in Android

  1. Android Registration Form – User will be able to register using his Name, Email, Age and Sex. On successful registration, user credentials will be stored on the DB created in our backend server. There will be a link to Android Login Screen for the already registered user.
  2. Android Login screen – An already registered user can login here. User entered data will be verified against data stored in backend server before successful login. There will be a link to the android registration form if the user is not already registered.
  3. User activity – Once the user has entered correct email and password in Android Login screen, he will be taken to this activity and shown a welcome message along with his name.

    We will be using Android Volley library for handling the network requests. If you are not comfortable with features and usage of Volley then please go through our tutorial of Android Volley.

    We will use Android Volley Library to send the user login and registration details in a POST request. This will handle our network requests pertaining to Login and Registration Form in Android




    Pre-requisites for Login and Registration Form in Android

    1. Android Studio installed on your PC (Unix or Windows). You can learn how to install it here .
    2. A real time android device (Smartphone or Tablet) configured with Android Studio. .
    3. Basic knowledge of JSON Parsing, Refer to JSON Parsing Tutorial. to learn about parsing JSON response.
    4. Working knowledge of Android Volley, Refer to JSON Parsing Tutorial. to learn about using Volley.
    5. We are also using Floating Label Edit Text for the input EditText, if you want you can go through the following Floating Label Edit Text tutorial.
    6. Important: Don’t proceed further if you don’t have a server running on your localhost or you haven’t created the PHP API, that will handle Login and Registeration data from the android app. In case you haven’t done this, please refer to Android Login and Registration with PHP MySQL Tutorial first and then continue from here.

    Creating a New Project and Adding Volley

    1. Go to File → New → New Project and enter your Application Name.
    2. Enter Company Domain, this is used to uniquely identify your App’s package worldwide.
    3. Choose project location and minimum SDK and on the next screen choose Empty Activity, since we would be adding most of the code Ourselves. Then Click on Next.
    4. Choose an Activity Name. Make sure Generate Layout File check box is selected, Otherwise we have to generate it ourselves.Then click on Finish. We are using the Activity Name as LoginActivity. It represents Android Login screen for our app.
    5. Gradle will configure your project and resolve the dependencies, Once it is complete proceed for next steps.
    6. To add Volley to your project add the following dependency in your App’s build.gradle file.
    compile 'com.android.volley:volley:1.0.0'
    

    Add Internet Permission

    Add the following permission to your AndroidManifest.xml file

    AndroidManifest.xml

    Setup Request Queue for Android Volley Library

    We will set up a single object of RequestQueue for the complete lifecycle of our Login and Registration Form in Android app. So create a singleton class and add RequestQueue object as member field and create methods to achieve the functionality offered by Volley.
    Create a new java class AppSingleton.java and copy the code from the following link

    AppSingleton.java

    We will use the method addToRequestQueue() to add our request to the request queue of volley.

    Creating Login screen

    Android Login screen Layout

    Create a file activity_login.xml and add the following code:

    
        
    

    We are using Floating Label Edit Text for all input fields in Login and Registration Form in Android. The layout for Android Login Screen is very simple, we are taking email and passwords as input from the user.

    Then we have a Button for Login and one button for taking the user to the Android Registration Form in case user is not registered already.

    Android Login Screen Activity

    Open LoginActivity.java and add the following code.

    package com.androidtutorialpoint.androidlogin;
    
    import android.app.ProgressDialog;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.widget.Button;
    import android.widget.EditText;
    import android.content.Intent;
    import android.view.View;
    import android.widget.Toast;
    import com.android.volley.Request;
    import com.android.volley.Response;
    import com.android.volley.VolleyError;
    import com.android.volley.toolbox.StringRequest;
    import org.json.JSONException;
    import org.json.JSONObject;
    import java.util.HashMap;
    import java.util.Map;
    
    
    public class LoginActivity extends AppCompatActivity {
    
        private static final String TAG = "LoginActivity";
        private static final String URL_FOR_LOGIN = "http://XXX.XXX.X.XX/android_login_example/login.php";
        ProgressDialog progressDialog;
        private EditText loginInputEmail, loginInputPassword;
        private Button btnlogin;
        private Button btnLinkSignup;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_login);
            loginInputEmail = (EditText) findViewById(R.id.login_input_email);
            loginInputPassword = (EditText) findViewById(R.id.login_input_password);
            btnlogin = (Button) findViewById(R.id.btn_login);
            btnLinkSignup = (Button) findViewById(R.id.btn_link_signup);
            // Progress dialog
            progressDialog = new ProgressDialog(this);
            progressDialog.setCancelable(false);
    
            btnlogin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    loginUser(loginInputEmail.getText().toString(),
                            loginInputPassword.getText().toString());
                }
            });
    
            btnLinkSignup.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent i = new Intent(getApplicationContext(), RegisterActivity.class);
                    startActivity(i);
    
                }
            });
        }
    
        private void loginUser( final String email, final String password) {
            // Tag used to cancel the request
            String cancel_req_tag = "login";
            progressDialog.setMessage("Logging you in...");
            showDialog();
            StringRequest strReq = new StringRequest(Request.Method.POST,
                    URL_FOR_LOGIN, new Response.Listener() {
    
                @Override
                public void onResponse(String response) {
                    Log.d(TAG, "Register Response: " + response.toString());
                    hideDialog();
                    try {
                        JSONObject jObj = new JSONObject(response);
                        boolean error = jObj.getBoolean("error");
    
                        if (!error) {
                            String user = jObj.getJSONObject("user").getString("name");
                            // Launch User activity
                            Intent intent = new Intent(
                                    LoginActivity.this,
                                    UserActivity.class);
                            intent.putExtra("username", user);
                            startActivity(intent);
                            finish();
                        } else {
    
                            String errorMsg = jObj.getString("error_msg");
                            Toast.makeText(getApplicationContext(),
                                    errorMsg, Toast.LENGTH_LONG).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
    
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e(TAG, "Login Error: " + error.getMessage());
                    Toast.makeText(getApplicationContext(),
                            error.getMessage(), Toast.LENGTH_LONG).show();
                    hideDialog();
                }
            }) {
               @Override
                protected Map getParams() {
                    // Posting params to login url
                    Map params = new HashMap();
                    params.put("email", email);
                    params.put("password", password);
                    return params;
                }
            };
            // Adding request to request queue
            AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq,cancel_req_tag);
        }
    
        private void showDialog() {
            if (!progressDialog.isShowing())
                progressDialog.show();
        }
        private void hideDialog() {
            if (progressDialog.isShowing())
                progressDialog.dismiss();
        }
    }
    
    

    We have defined a constant URL_FOR_LOGIN where we have a listener for our Login Request. You need to replace the IP address for your server in this constant. We have a helper method loginUser() which takes in email and password, creates a new Volley Request and adds it to the RequestQueue.

    When the user clicks on the Login Button, the loginUser() is called with the input email and password. In this method we create a new StringRequest object.

    To create a new StringRequest Object, the constructor takes in three arguments.

    1. Url: the URL for the network request.
    2. Listener Object: anonymous inner type, an implementation of Response.Listener(), It has an onRespose method which will receive the string from the web.
    3. ErrorListener Object: anonymous inner type , an implementaion of onErrorResponse(VolleyError err) will get an instance of object of Volley Error
    4. In the onResponse() method, we are getting the response JSONObject from our login API and then determining, whether the login was successful or resulted in error. For this we are getting the value of error from the response. If there is no error, we get the user name from the the response and then start UserActivity.java passing the name of the user.

      In the case of an error, we are showing a Toast with the error message.
      In the onErrorResponse() method, we are simply logging the Volley error message to LogCat.

      The REQUEST_TAG is used to cancel the request

      We create a Map with email and password in the getParams() method. This is sent with the POST request that is sent to the server listening to Login and Registration requests.

      Now that we have the network request, We need to add the request to a queue, We get the instance of the RequestQueue from AppSingleton and add our request to the queue.

      In the onClickListener() for the btnLinkSignupNext we are sending the user to the Android Registration Form.

      Now let’s create the Android Registration Form for our Login and Registration Form in Android.

      Creating Android Registration Form

      Android Registration Form Layout

      Create a file activity_register.xml and add the following code:

      
              
          

      Again we are using Floating Label Edit Text for all input fields, the layout for Android Registration Form consists of input EditText for Name, Email, Password and Age. For the sex of the user, we have used RadioGroup consisting of RadioButton for Male and Female.

      Then we have a Button for Register and one button for taking the user to the Android Login Screen in case user is registered already and want’s to login.

      Android Registration Form Activity

      Open RegisterActivity.java and add the following code.

      package com.androidtutorialpoint.androidlogin;
      
      import android.app.ProgressDialog;
      import android.content.Intent;
      import android.os.Bundle;
      import android.support.v7.app.AppCompatActivity;
      import android.util.Log;
      import android.view.View;
      import android.widget.Button;
      import android.widget.EditText;
      import android.widget.RadioGroup;
      import android.widget.Toast;
      import com.android.volley.Request;
      import com.android.volley.Response;
      import com.android.volley.VolleyError;
      import com.android.volley.toolbox.StringRequest;
      import org.json.JSONException;
      import org.json.JSONObject;
      import java.util.HashMap;
      import java.util.Map;
      
      public class RegisterActivity extends AppCompatActivity {
      
          private static final String TAG = "RegisterActivity";
          private static final String URL_FOR_REGISTRATION = "http://XXX.XXX.X.XX/android_login_example/register.php";
          ProgressDialog progressDialog;
      
          private EditText signupInputName, signupInputEmail, signupInputPassword, signupInputAge;
          private Button btnSignUp;
          private Button btnLinkLogin;
          private RadioGroup genderRadioGroup;
      
          @Override
          protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_register);
      
              // Progress dialog
              progressDialog = new ProgressDialog(this);
              progressDialog.setCancelable(false);
      
              signupInputName = (EditText) findViewById(R.id.signup_input_name);
              signupInputEmail = (EditText) findViewById(R.id.signup_input_email);
              signupInputPassword = (EditText) findViewById(R.id.signup_input_password);
              signupInputAge = (EditText) findViewById(R.id.signup_input_age);
      
              btnSignUp = (Button) findViewById(R.id.btn_signup);
              btnLinkLogin = (Button) findViewById(R.id.btn_link_login);
      
              genderRadioGroup = (RadioGroup) findViewById(R.id.gender_radio_group);
              btnSignUp.setOnClickListener(new View.OnClickListener() {
                  @Override
                  public void onClick(View view) {
                      submitForm();
                  }
              });
              btnLinkLogin.setOnClickListener(new View.OnClickListener() {
                  @Override
                  public void onClick(View view) {
      
                      Intent i = new Intent(getApplicationContext(),LoginActivity.class);
                      startActivity(i);
                  }
              });
          }
      
          private void submitForm() {
      
              int selectedId = genderRadioGroup.getCheckedRadioButtonId();
              String gender;
              if(selectedId == R.id.female_radio_btn)
                  gender = "Female";
              else
                  gender = "Male";
      
              registerUser(signupInputName.getText().toString(),
                           signupInputEmail.getText().toString(),
                           signupInputPassword.getText().toString(),
                           gender,
                           signupInputAge.getText().toString());
          }
      
          private void registerUser(final String name,  final String email, final String password,
                                    final String gender, final String dob) {
              // Tag used to cancel the request
              String cancel_req_tag = "register";
      
              progressDialog.setMessage("Adding you ...");
              showDialog();
      
              StringRequest strReq = new StringRequest(Request.Method.POST,
                      URL_FOR_REGISTRATION, new Response.Listener() {
      
                  @Override
                  public void onResponse(String response) {
                      Log.d(TAG, "Register Response: " + response.toString());
                      hideDialog();
      
                      try {
                          JSONObject jObj = new JSONObject(response);
                          boolean error = jObj.getBoolean("error");
      
                          if (!error) {
                              String user = jObj.getJSONObject("user").getString("name");
                              Toast.makeText(getApplicationContext(), "Hi " + user +", You are successfully Added!", Toast.LENGTH_SHORT).show();
      
                              // Launch login activity
                              Intent intent = new Intent(
                                      RegisterActivity.this,
                                      LoginActivity.class);
                              startActivity(intent);
                              finish();
                          } else {
      
                              String errorMsg = jObj.getString("error_msg");
                              Toast.makeText(getApplicationContext(),
                                      errorMsg, Toast.LENGTH_LONG).show();
                          }
                      } catch (JSONException e) {
                          e.printStackTrace();
                      }
      
                  }
              }, new Response.ErrorListener() {
      
                  @Override
                  public void onErrorResponse(VolleyError error) {
                      Log.e(TAG, "Registration Error: " + error.getMessage());
                      Toast.makeText(getApplicationContext(),
                              error.getMessage(), Toast.LENGTH_LONG).show();
                      hideDialog();
                  }
              }) {
                  @Override
                  protected Map getParams() {
                      // Posting params to register url
                      Map params = new HashMap();
                      params.put("name", name);
                      params.put("email", email);
                      params.put("password", password);
                      params.put("gender", gender);
                      params.put("age", dob);
                      return params;
                  }
              };
              // Adding request to request queue
              AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq, cancel_req_tag);
          }
      
          private void showDialog() {
              if (!progressDialog.isShowing())
                  progressDialog.show();
          }
      
          private void hideDialog() {
              if (progressDialog.isShowing())
                  progressDialog.dismiss();
          }
      }
      

      The code is similar to the Android Login Screen Activity. First we have defined a constant URL_FOR_REGISTRATION where we have a listener for our Registeration Request. We have a helper method submitForm() which takes in user details, creates a new Volley Request and adds it to the RequestQueue.

      If the registration is successful, the user data is stored in the MySQL database in our backend Database.

      In the submitForm() method, We have created a new StringRequest Object similar to one in the LoginActivity.
      In the onResponse() method, we are getting the response JSONObject and then determining, whether the registeration was successful or resulted in error. For this we are getting the value of error from the response. If there is no error, we get the user name from the response and show a Toast message that the registeration is successful, next we start LoginActivity.java passing the name of the user.

      In the case of an error, we are showing a Toast with the error message.
      In the onErrorResponse() method, we are simply logging the Volley error message to LogCat.

      We create a Map with user details in the getParams() method. This is added to the POST request that is sent to our backend server.

      Now that we have the network request, We need to add the request to a queue, We get the instance of the RequestQueue from AppSingleton and add our request to the queue.

      Next add entries for a RegisterActivity and UserActivity in the AndroidManifest.xml file. The complete Manifest file for Login and Registration Form in Android should be as follows.

      AndroidMainfest.xml

      Now run the app for Login and Registration Form in Android, if you have correctly setup your localhost as in Android Login and Registration with PHP MySQL Tutorial, you should be able to register and then login to your app.




      What’s Next?

      With the knowledge of Login and Registration Form in Android, you can create any app which requires user login like some social networking app, chat app. You can try to integrate Google Login in your app, and once the user is logged in you can show his profile in the UserActivity. For more details how to Add Google Login to your Android App Refer the following link. :Adding Google Login To Android App. Similarly you can add Facebook Login to your Android App and show user profile in the navigation drawer. Please refer to the following link to learn how to Add Facebook Login to Your Android Application. :Adding Facebook Login To Android App

      For more awesome tutorials stay tuned .. and Don’t forget to subscribe our blog for latest android tutorials.

      Also do Like our Facebook Page or Add us on Twitter.

      Click on Download Now button to download the full code.




      The post Login and Registration Form in Android appeared first on Android Tutorial Point.



This post first appeared on Android Tutorial Point, please read the originial post: here

Share the post

Login and Registration Form in Android

×

Subscribe to Android Tutorial Point

Get updates delivered right to your inbox!

Thank you for your subscription

×