Android Login and Register with SQLite Database Tutorial

In software applications, it is mostly required to store user’s and app data locally. Android SDK provides several api’s for developers to save user and app data, So SQLite is one of the way of storing data. For many applications, SQLite is the apps backbone whether it’s used directly or via some third-party wrapper. In this tutorial we will see how to use SQLite in our app directly.

What is SQLite?

SQLite is a lightweight database which comes with android. It is an Open-Source embedded SQL database engine. This provides relational database management structure for storing user defined records in the form of tables.

Key point to understand regarding SQLite :-

– SQLite is RDBMS (Relational Database Management System)
– SQLite is written in C programming language
– SQLite is embedded within the Android operating System, so you don’t need anything external on Android to use SQLite
– To manipulate data (insert, update, delete) in SQLite database – we’ll use SQL (Structured Query Language)

Let’s Get it Working

In this tutorial we are going to learn how to use SQLite. To really understand the usage of SQLite we will create an app . The App contains simple Login form, Registration form and listing of registered user. This app shows how SQLite database operations are performed. I assume that you have created a new android project. Source Code is available on GitHub.

DownloadCode
 
github

Step 1) Update build.gradle file.

Before you can use Material Design in your projects you need to add the following compile line to your Gradle dependencies block in your build.gradle file and rebuilt the project .

Step 2) Update strings.xml.

Add the below string values to the string.xml located in res => values => strings.xml.

Step 3) Update colors.xml.

Add the below color values to the colors.xml located in res => values => colors.xml.

Step 4) Update styles.xml.

Add the below style values to the styles.xml located in res => values => styles.xml.

Step 5) Add Logo Image.

Download the below logo image and add it to the drawable folder located in res => drawable.

Android Tutorials Hub Logo

Android Tutorials Hub Logo

Step 6) Create User model class.

Create a new package named modal and create User class with all getter and setter methods to maintain single contact as an object.

Step 7) Create DatabaseHelper class.

Create a new package named sql and create DatabaseHelper class. Extend this class with SQLiteOpenHelper to manage database creation and version management. I have also written some method to manipulate data in database.

Methods and functionality

addUser :- add user to database.
getAllUser :- fetch users data from database.
updateUser :- update user in database on the basis of user id.
deleteUser :- delete user from database on the basis of user id.
checkUser :- check whether user exists in database.

User Table Schema

User Table Schema

Step 8) Create activity_login.xml.

Now create a layout file for the LoginActivity.java i.e activity_login.xml and add the below code in your layout file. The code will create a simple login form containing logo on the top, 2 input fields email and password, login button and registration screen navigation link.

activity_login.xml would result a screen like this:

Login Screen

Login Screen

Step 8) Create InputValidation class.

Create a package named helpers and create a class in it named InputValidation.java and add below code in it. The code will create validation methods for input field. Validation like empty input, valid email and etc.





Step 9) Create LoginActivity class.

Now create a package named activities and create a class named LoginActivity and add below code. Here i have written the code to validate the input fields Email and Password using the InputValidation class which i described above. Also code for navigation to registration screen on the click of registration link and to user list screen after click on login button if credentials are valid.

The Screen below shows the login form with input validation display the error message if values entered in input fields are not valid.

Login Screen with Input Validation

Login Screen with Input Validation

The Screen below shows the login form with input validation display the snack bar with message if values entered in input fields are not validated from SQLite database.

Login Screen With SQLite Validation

Login Screen With SQLite Validation

Step 10) Create activity_register.xml.

Now create a layout file for the RegisterActivity.java i.e activity_register.xml and add the below code in your layout file. The code will create a simple registration form containing logo on the top, 4 input fields name, email, password and confirm password, register button and login screen navigation link.

activity_register.xml would result a screen like this:

Registration Screen

Registration Screen

Step 11) Create RegisterActivity class.

Now create a package named activities and create a class named RegisterActivity and add below code. Here i have written the code to validate the input fields Name, Email, Password and Confirm Password using the InputValidation class which i described above. Also code for navigation to login screen on the click of login link and shows snackbar with success message for registration.

The Screen below shows the register form with input validation display the error message if values entered in input fields are not valid.

Register Screen with Input Validation

Register Screen with Input Validation

The Screen below shows the filled register form with valid values.

Register Screen with input fields filled

Register Screen with filled input fields

The Screen below shows the register form display the snackbar with registration success message.

Register Screen with Registration Success Message

Register Screen with Registration Success Message

Step 12) Create activity_users_list.xml.

Now create a layout file for the UsersListActivity.java i.e activity_users_list.xml and add the below code in your layout file. The code will create a simple view containing two views one view i.e LinearLayout shows the welcome message with email id of the logged in user and other view i.e RecyclerView shows the list of registered users in the app.

activity_users_list.xml would result a screen like this:

User List Screen

User List Screen

Step 13) Writing the Adapter Class.

Now create a package named adapters and create a class named UsersRecyclerAdapter and add below code. Here onCreateViewHolder() method inflates item_user_recycler.xml. In onBindViewHolder() method the appropriate User data (name,email and password) set to each row.

item_user_recycler.xml

Step 14) Create UsersListActivity class.

Now create a package named activities and create a class named UsersListActivity and add below code. Here i have written the code to show the email id of the logged in user and the list of registered users.

The Screen below after user login shows the brand name, email id of logged in user and registered users list.

User List Screen After Login

User List Screen After Login

Step 15) Update AndroidManifest.xml.

DownloadCode
 
github


Enjoy Coding and Share Knowledge

  • Streatico HD

    Can you do another tutorial but this time the person just logs in or registers and they are taken to the home page. Finally how do you hide the usernames password from appearing in the homepage.

    thanks Please reply back

    • Admin

      Yes sure i will write new tutorial for that , But you can also use this sample with bit modification. You can do it by replacing activity name in object of intent in LoginActivity.
      Steps are:
      – Go to verifyFromSQLite() method in LoginActivity
      – There is a code in this function that make app navigates to UsersListActivity
      Intent accountsIntent = new Intent(activity, UsersListActivity.class);
      accountsIntent.putExtra(“EMAIL”, textInputEditTextEmail.getText().toString().trim());
      emptyInputEditText();
      startActivity(accountsIntent);
      – Replace the above code with your HomePage page intent like
      Intent homePageIntent = new Intent(activity, HomePage.class);
      emptyInputEditText();
      startActivity(homePageIntent);

      Hope this may help you 🙂

  • Sandeep

    How would i go about adding more things for them to register for example date of birth, age , weight but still only require username and pass for login, i hope to use the data stated later on in my program.
    Any help would be appreciated

    • Admin

      You have to add more input views in activity_register.xml to accept values like date of birth ,age , weight and etc. After adding views you have to modify the RegisterActivity to accept inputs from user and add logic to store data in database. Also have to update create table query in DatabaseHelper class to add more columns.
      Hope this may help u. If any doubt feel free to ask 🙂

  • Pooja Ravi

    I tried passing an intent to a class called years on clicking the login button like this:
    Intent yearIntent = new Intent(activity, years.class);
    startActivity(yearIntent);
    but the app crashes.Here’s the code for years.class:
    package com.example.android.demo1.activities;

    import android.content.Intent;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.view.View;

    import com.example.android.demo1.R;
    import com.example.android.demo1.firstyear;
    import com.example.android.demo1.fourthyear;
    import com.example.android.demo1.secondyear;
    import com.example.android.demo1.thirdyear;

    /**
    * Created by pooja on 20-01-2017.
    */

    public class years extends AppCompatActivity
    {
    @Override
    protected void onCreate( Bundle savedInstanceState)
    {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.years);
    }
    public void openFirstYear(View view)
    {
    Intent i = new Intent( this, firstyear.class);
    startActivity(i);
    }
    public void openSecondYear(View view)
    {
    Intent i = new Intent(this, secondyear.class);
    startActivity(i);
    }
    public void openThirdYear(View view)
    {
    Intent i = new Intent(this, thirdyear.class);
    startActivity(i);
    }
    public void openFourthYear(View view)
    {
    Intent i = new Intent(this, fourthyear.class);
    startActivity(i);
    }
    }
    Please help me.
    Thank You.

    • Admin

      Have you declared years activity in AndroidManifest.xml. Or post the specific error from the logs.

      Hope this may help you 🙂

  • Arnold

    Hi i would like to ask why after i click register button my app crash, i tried to copy and paste all you’ve posted above, so no change happens.

    • Arnold

      nevermind found the error, its in your Validation if you remove

      else {
      textInputLayout.setErrorEnabled(false);
      }

      the app wont crash

      • Admin

        Great ☺️

        • frans ringo

          Hi fellas!
          i got a same problem with Arnold when i using your code. I’ve deleted

          else
          {textInputLayout.setErrorEnabled(false);
          }

          i just got the same error. My LogCat Says,

          java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.support.design.widget.TextInputLayout.setError(java.lang.CharSequence)’ on a null object reference

          When the pointer says, i must change something on, postDataToSQlite, onClick, and inputValidation. I don’t understand what problem did i got.

          • Admin

            Hi Frans ringo,

            textInputLayout.setErrorEnabled(false); function is to only to disable the error message of TextInputEditText . The error that you have mentioned show that you are performing the operation on any object without making reference of that. so please check that.

            Hope this may help you , Feel free to ask 🙂

            Thanks

          • frans ringo

            After i’m tring to use my own validation, i can’t create method for checkUser (for login) and addUser (for register). But i still using your table creating method. Can u help me with my problem? i’ll post the part of my code,

            validation for my login

            masuk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            if (nope.getText().toString().trim().length()==0){
            nope.setError(“Masukkan Nomor Handphone Anda”);
            nope.requestFocus();
            }
            else if (sandi.getText().toString().trim().length()==0){
            sandi.setError(“Masukkan Kata Sandi Anda”);
            nope.requestFocus();
            }
            else{emptyInputEditText();
            Toast.makeText(getApplicationContext(),
            “Selamat Datang”, Toast.LENGTH_LONG).show();
            startActivity(new Intent(ActivityLogin.this, ActivityHome.class));
            }
            }
            });

            and this is the part of my register validation

            daftar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            if (nope.getText().toString().trim().length()==0){
            nope.setError(“Masukkan Nomor Handphone Anda”);
            nope.requestFocus();
            }
            else if (nama.getText().toString().trim().length()==0){
            nama.setError(“Masukkan Nama Lengkap Anda”);
            nama.requestFocus();
            }
            else if (sandi.getText().toString().trim().length()==0){
            sandi.setError(“Masukkan Kata Sandi Anda”);
            nope.requestFocus();
            }
            else if (sandi.getText().toString().trim().length() < 6){
            sandi.setError("Masukkan Kata Sandi Minimal 6 Karakter");
            sandi.requestFocus();
            }
            else if (konfSandi.getText().toString().trim().length()==0){
            konfSandi.setError("Masukkan Konfirmasi Kata Sandi Anda");
            sandi.requestFocus();
            }
            else if (!konfSandi.getText().toString().equals(sandi.getText().toString())){
            konfSandi.setError("Konfirmasi Kata Sandi Anda Tidak Sama Dengan Kata Sandi Anda");
            sandi.requestFocus();
            }
            else if (email.getText().toString().trim().length()==0){
            email.setError("Masukkan Alamat Email Anda");
            email.requestFocus();
            }
            else if (kota.getText().toString().trim().length()==0){
            kota.setError("Masukkan Kota Tempat Anda Tinggal");
            kota.requestFocus();
            }
            else if (provinsi.getText().toString().trim().length()==0){
            provinsi.setError("Masukkan Provinsi Tempat Anda Tinggal");
            provinsi.requestFocus();
            }
            else{emptyInputEditText();
            Toast.makeText(getApplicationContext(),
            "Terimakasih Sudah Mendafatar di Gampang Material" + nama.getText() , Toast.LENGTH_LONG).show();
            startActivity(new Intent(ActivityDaftar.this, ActivityHome.class));
            }

            }
            });

            i'm sorry for being so stubborn :')

  • Streatico HD

    Hi, I tried running this in a virtual device with api 24 and it doesnt show the database data file in android device monitor? Can you help

    • Admin

      Follow the steps:-
      Tools > Android > Android Device Monitor
      Your database file will be in this path DDMS–> file explorer–>data–> data–> your package name–>databases

      Hope this may help u 🙂

  • Jitesh

    I have put no validation and when I click on the signup button my app crashes. I tried running it on debug but as soon as it reaches the databasehelper.checkuser method my app crashes. Can you please help me on this?

    • Admin

      Hello Jiten,

      Can you please share the code and error logs that i can look into it.

      Thanks

Show Buttons
Hide Buttons