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

Please feel free to comment as well as ask questions. And, yeah! If this post helps you please do share!

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 🙂

    • shashi patil

      whats the error

  • 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

  • Abhimanyu Dasarwar

    when i click on create new button app crashes?any solutions

    • Kusnadi

      show ur logcat

  • Mohd Shahdan Bin Addenan

    hi admin..thx to your article, I managed to get your code running fine in my laptop & emulate thru my handphone. I want to ask 2 question.

    1-I already enable button delete & update in activity_users_list.xml, how do I link this button to delete & update function in SQLite DatabaseHelper?

    2-If I want to add more user data data in RegisterActivity, which file should I update?

    thx in advance for the guidance…

    • Admin

      Hello Shahdan,

      1) Use the following mentioned methods for your requirement of update and delete . These methods are defined in DatabaseHelper class. Both of the function requires user object as arguments so call these function with corresponding user object you want to update or delete.
      /**
      * This method to update user record
      *
      * @param user
      */
      public void updateUser(User user) {
      SQLiteDatabase db = this.getWritableDatabase();

      ContentValues values = new ContentValues();
      values.put(COLUMN_USER_NAME, user.getName());
      values.put(COLUMN_USER_EMAIL, user.getEmail());
      values.put(COLUMN_USER_PASSWORD, user.getPassword());

      // updating row
      db.update(TABLE_USER, values, COLUMN_USER_ID + ” = ?”,
      new String[]{String.valueOf(user.getId())});
      db.close();
      }

      /**
      * This method is to delete user record
      *
      * @param user
      */
      public void deleteUser(User user) {
      SQLiteDatabase db = this.getWritableDatabase();
      // delete user record by id
      db.delete(TABLE_USER, COLUMN_USER_ID + ” = ?”,
      new String[]{String.valueOf(user.getId())});
      db.close();
      }

      2) If you want to add more data in register activity you have to update the UI for register activity , Database table structure that is defined in DatabaseHelper Class and also the User class.

      Hope this may help you , Feel free to ask 🙂

      Thanks

      • dheena_dayalan

        hi admin i want to update my data stored in sqllite database.. i am using your code itself. i saw the update query. but i didnot how to use that method for an update in the program. can you help me please

        • dheena_dayalan

          I have created Sqlite database in app. when I clear data from settings->applications->manage applications the Sqlite db removed. any suggestions to keep sqlite database as it is.

          • Admin

            Hello Dheena,

            Yes you can keep the sqlite as it is, as by default sqlite database file is stored in app folder. To keep Sqlite database file you have to change the location of the sqlite file programatically.

            Like :- Environment.getExternalStorageDirectory()+File.separator+”foldername”+File.separator+”database_name.db”

            Code Snippet :-
            public class MySQLiteOpenHelper extends SQLiteOpenHelper {
            MySQLiteOpenHelper(Context context) {
            super(context,Environment.getExternalStorageDirectory()+File.separator+”foldername”+File.separator+”database_name.db”, null, 0);
            }
            }
            But before doing that please check that SD card is mounted or not.
            Follow this link for storage related operations :- https://developer.android.com/guide/topics/data/data-storage.html

            Hope this may help you , Feel free to ask 🙂

            Thanks

    • Hassan Ali Mughal

      Sir kindly you snd the backend of this two buttons??

      • Lalit Vasan

        Hi Hassan Ali,

        What do you mean by backend?

        • Hassan Ali Mughal

          Hi admin
          the backend of update ur deleteuser buttons

          • Lalit Vasan

            SQLite is the backend used in this demo.

            And to delete any user there is a method named deleteUser(User user) in DatabaseHelper class. Pass the user’s object which you want to delete.

          • Hassan Ali Mughal

            Hi admin
            Because the update ur deleteUser are never used in Database helper class, used these button front ends in .xml in list ur recycle adapter?? and its .java activity??

  • Ajoo

    Hello, what do i need to do if i want to show Users single? Like if i log in with Sonja, only her information will come up, i almost have it but im stuck. i just want to get one user from db.
    But getOneUser.
    public List getAllUsers(){
    String[] columns = {COLUMN_USER_ID, COLUMN_USER_NAME,
    COLUMN_USER_EMAIL, COLUMN_USER_PASSWORD
    };
    String sortOrder = COLUMN_USER_NAME + ” ASC”;
    List userList = new ArrayList();
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query(TABLE_USER,
    columns,
    null,
    null,
    null,
    null,
    sortOrder);
    //går igenom listan och lägger till
    if(cursor.moveToFirst()){
    do{
    User user = new User();
    user.setId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(COLUMN_USER_ID))));
    user.setFullname((cursor.getString(cursor.getColumnIndex(COLUMN_USER_NAME))));
    user.setEmail((cursor.getString(cursor.getColumnIndex(COLUMN_USER_EMAIL))));
    user.setPassword((cursor.getString(cursor.getColumnIndex(COLUMN_USER_PASSWORD))));

    userList.add(user);

    }while (cursor.moveToNext());
    }
    cursor.close();
    db.close();
    // returnerar listan
    return userList;
    }

    • Admin

      Hello Ajoo,

      Use the below function,this will return user data on the basis of email and password.
      /**
      * This method to return user data if exist or return null if not exist
      *
      * @param email
      * @param password
      * @return User/null
      */
      public User getUser(String email, String password) {

      // array of columns to fetch
      String[] columns = {
      COLUMN_USER_ID,
      COLUMN_USER_EMAIL,
      COLUMN_USER_NAME,
      COLUMN_USER_PASSWORD
      };
      SQLiteDatabase db = this.getReadableDatabase();
      // selection criteria
      String selection = COLUMN_USER_EMAIL + ” = ?” + ” AND ” + COLUMN_USER_PASSWORD + ” = ?”;

      // selection arguments
      String[] selectionArgs = {email, password};

      // query user table with conditions
      /**
      * Here query function is used to fetch records from user table this function works like we use sql query.
      * SQL query equivalent to this query function is
      * SELECT user_id,user_name,user_email,user_password FROM user WHERE user_email = ‘jack@androidtutorialshub.com’ AND user_password = ‘qwerty’;
      */
      Cursor cursor = db.query(TABLE_USER, //Table to query
      columns, //columns to return
      selection, //columns for the WHERE clause
      selectionArgs, //The values for the WHERE clause
      null, //group the rows
      null, //filter by row groups
      null); //The sort order

      if (cursor.moveToFirst()) {
      User user = new User();
      user.setId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(COLUMN_USER_ID))));
      user.setName(cursor.getString(cursor.getColumnIndex(COLUMN_USER_NAME)));
      user.setEmail(cursor.getString(cursor.getColumnIndex(COLUMN_USER_EMAIL)));
      user.setPassword(cursor.getString(cursor.getColumnIndex(COLUMN_USER_PASSWORD)));
      cursor.close();
      db.close();
      return user;
      }

      cursor.close();
      db.close();

      return null;
      }

      Hope this may help you , Feel free to ask 🙂

      Thanks

      • Ajoo

        thanks for answering, i saw the problem when you posted it i forgot to put in
        String selection = COLUMN_USER_EMAIL + ” = ?” + ” AND ” + COLUMN_USER_PASSWORD + ” = ?”;

        // selection arguments
        String[] selectionArgs = {email, password};

        But then i need to change this ?
        private void getDataFromSQLite() {
        new AsyncTask() {
        @Override
        protected Void doInBackground(Void… params) {
        userList.clear();
        userList.addAll(dbHelper.getAllUsers()); —————– to something like db.getUser(String email, String name): ?
        return null;
        }

        • Admin

          Hello Ajoo,

          getUser() function will return the object of the User . so no need to put in array list. Directly make an instance of user like User user = db.getUser(email,password);
          and then you can access all the fields via get functions like user.getName();

          Hope this may help you , Feel free to ask 🙂
          Thanks

          • Ajoo

            Could you explain
            new AsyncTask() {
            @Override
            protected Void doInBackground(Void… params) { ?

          • Admin
          • Ajoo

            Hello, just wanted to say, thanks for all the info, helps me alot, so fun to learn Android/Java. But the info you gave me earlier works for 2 secs then it ceshes, i think its my codes fault.
            You seems to be the God of coding.
            Thanks.

          • Mon Ange

            i didnt get it

  • Ho Voon Hoong

    Hi, May I ask that how to login as the user as normal user or admin to access the different xml? For instance, normal user login to xml 1 while admin login to xml 2? Thx

    • Admin

      Hello Ho Voon Hoong,

      There are many ways to solve the problem you have asked, following are the ways:-

      1) Create Two different activity , one for normal user and second for admin. Declare it in manifest.xml. On login check whether logging in user is admin or normal user and redirect it to desired activity
      For Example:-
      //admin = 0 and user = 1
      if(user.getType == 0){
      // Open Admin Activity
      Intent intent = new Intent(getApplicationContext(),AdminActivity.class);
      startActivity(intent);

      }else{
      // Open User Activity
      Intent intent = new Intent(getApplicationContext(),UserActivity.class);
      startActivity(intent);
      }

      2) You can use same activity for both case but you have to put a condition on setContentView(/*layout*/);
      For Example:-

      //admin = 0 and user = 1
      if(user.getType == 0){
      setContentView(/*layout for admin*/);
      }else{
      setContentView(/*layout for user*/);
      }

      Hope this may help you , Feel free to ask 🙂

      Thanks

      • Ho Voon Hoong

        thank you for your help

      • Ho Voon Hoong

        Hi, sorry to ask you late time but can you please write the code of how to add admin and normal user in the manifest.xml and how to add in the login check? I try but still can’t do that…Thank you

      • Chris Brown

        Which files need to be changed to make this happen? So far im assuming you edit AndroidManifest.xml, Does that code needs pasted within </Manifest or </application? and UserActivity.class needs to be changed to the .class you want to open?

        Most of us are pretty new to this, im trying to learn as i build an app. Could you give a bit more of your professional insight on what exactly needs done to implement this?
        Ideally, id like Admin to go to your activity_users_list.xml, and standard users to go to activity_main.xml.

        Could you help me out please buddy? Thanks.

        btw, Your tutorial was awesome, best i had found. Taught me a lot. I'm very grateful.

      • Chris Brown

        Thanks again for everything Admin, I learned alot for you/this tutorial…Much appreciated. Any chance you could Help me figure this part out? Id like to make it go to UserListActivity for admin users and to MainScreenActivity for regular users.

  • Salwa Hegazy

    Hi, May i ask that why when try to login or register give me NullpointerException ?

    • Admin

      Hello Salwa Hegazy,

      Can you please show the log error messages

      Thanks

      • Salwa Hegazy

        thanks dear , i solve the problem … Thanks for your reply 🙂

        • Salwa Hegazy

          but may i ask about a good way to sync sqlite to server and make connection ? thanks in advance 🙂

  • Deependra

    While running emulator, it shows following error. Kindly help.
    E/EGL_emulation: tid 2844: eglSurfaceAttrib(1165): error 0x3009 (EGL_BAD_MATCH)
    W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xaa4135c0, error=EGL_BAD_MATCH

    • Admin

      Hello Deependra,

      Your memory might not be enough to load all of the startup data. please raise it first while creating emulator.

      Hope this may help you , Feel free to ask 🙂

      Thanks,

  • dheena_dayalan

    hi admin, i want to update my data stored in sqllite database.. i am using your code itself. i saw the update query. but i did not how to use that method for an update in the program. can you help me please

    see my coding :
    public class ListActivity extends AppCompatActivity {

    private TextView textName;
    private RecyclerView recyclerViewUsers;
    private List listUsers;
    private RecyclerAdapter recyclerAdapter;
    RecyclerAdapter.UserViewHolder holder;
    private DatabaseHandler databaseHelper;
    View view;
    private String rowID = null;
    User user;

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

    initViews();

    initObjects();

    }

    private void initViews() {

    textName = (TextView) findViewById(R.id.textViewName);
    final CharSequence[] items = {Constants.UPDATE, Constants.DELETE};

    recyclerViewUsers = (RecyclerView) findViewById(R.id.recyclerViewUsers);
    // recyclerViewUsers.setTag(user.getId());

    recyclerViewUsers.addOnItemTouchListener(
    new RecyclerItemClickListener(ListActivity.this, new RecyclerItemClickListener.OnItemClickListener() {
    @Override public void onItemClick(final View view, final int position) {

    AlertDialog.Builder builder = new AlertDialog.Builder(ListActivity.this);
    builder.setItems(items, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
    if (which == 0) {

    user = listUsers.get(position);
    databaseHelper.deleteUser(user);
    recyclerAdapter.notifyDataSetChanged();

    } else {
    AlertDialog.Builder deleteDialogOk = new AlertDialog.Builder(ListActivity.this);
    deleteDialogOk.setTitle(“Delete Contact?”);
    deleteDialogOk.setPositiveButton(“Ok”, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {

    user = listUsers.get(position);
    databaseHelper.deleteUser(user);
    recyclerAdapter.notifyDataSetChanged();
    getDataFromSQLite();
    }
    }
    );
    deleteDialogOk.setNegativeButton(“Cancel”, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
    dialog.dismiss();
    }
    });
    deleteDialogOk.show();
    }
    }
    });
    AlertDialog alertDialog = builder.create();
    alertDialog.show();
    }
    }));

    }

    private void initObjects() {

    listUsers = new ArrayList();
    recyclerAdapter = new RecyclerAdapter(listUsers);

    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
    recyclerViewUsers.setLayoutManager(mLayoutManager);
    recyclerViewUsers.setItemAnimator(new DefaultItemAnimator());
    recyclerViewUsers.setHasFixedSize(true);
    recyclerViewUsers.setAdapter(recyclerAdapter);
    databaseHelper = new DatabaseHandler(ListActivity.this);

    String emailFromIntent = getIntent().getStringExtra(“EMAIL”);
    textName.setText(emailFromIntent);

    getDataFromSQLite();
    }

    private void getDataFromSQLite() {

    new AsyncTask() {
    @Override
    protected Void doInBackground(Void… params) {
    listUsers.clear();
    listUsers.addAll(databaseHelper.getAllUser());
    return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
    super.onPostExecute(aVoid);
    recyclerAdapter.notifyDataSetChanged();
    }
    }.execute();
    }

    }

    • Admin

      Hello Dheena,

      To use update function defined in database helper (function written below), you have to call the it like
      db.updateUser(/* pass the user object*/);

      The updateUser(User user) function will update the user information in database on the basis of unique user id.

      /**
      * This method to update user record
      *
      * @param user
      */
      public void updateUser(User user) {
      SQLiteDatabase db = this.getWritableDatabase();

      ContentValues values = new ContentValues();
      values.put(COLUMN_USER_NAME, user.getName());
      values.put(COLUMN_USER_EMAIL, user.getEmail());
      values.put(COLUMN_USER_PASSWORD, user.getPassword());

      // updating row
      db.update(TABLE_USER, values, COLUMN_USER_ID + ” = ?”,
      new String[]{String.valueOf(user.getId())});
      db.close();
      }

      Hope this may help you , Feel free to ask 🙂

      Thanks

      • dheena_dayalan

        ya i know this method sir, but i dont know where to change the data.

        • Admin

          Hello Dheena,

          Put a click listener on Recycler View . follow this link to put click listener on recycler view:- http://www.androidtutorialshub.com/android-recyclerview-click-listener-tutorial/ and then you will get an index of item clicked . From this index you will be able to retrieve user object from the user’s array list wrt to index. So make an activity or a dialog where you can show that values retrieved from arraylist in edit text and modify the values and call the updatUser(user) function by creating the user object will modified value dont forget to put user id in it.

          Hope this may help you , Feel free to ask 🙂

          Thanks

          • dheena_dayalan

            i set the listener perfectly. delete is working but i dont know how to update using that user id can i have an sample code for that please

  • AndroidDevloper

    Hİ,I want to go to the profile page of the login button

    • Admin

      Hello AndroidDevloper,

      In this tutorial after login app navigates to the user listing page . you can modify it to profile page by not showing the user’s list.

      Hope this may help you , Feel free to ask 🙂

      Thanks

      • Hemashri R M

        Hey admin,
        What am i supposed to do to display only the user who logs in instead of all the users in All Accounts?

        • Admin

          Hi Hemashri,

          Remove the RecyclerView and the functionality associated with it like adapter and all.

          Hope this may help you , Feel free to ask 🙂

          Thanks

          • Hemashri R M

            Thanks admin,
            But it will show me a blank page in All Accounts if i remove the Recycle View and the adapter.

  • Arij

    Hi admin i have a problem with “R” and the ” import com.androidtutorialshub.loginregister.R;” is red, i think there’s an R class missing, please help bcz i liked this tutorial but there’s only that problem ! please replay soon !!!

    • Admin

      Hello Arij,

      In Android Studio, click on Build option you will get some options there . So firstly select “Clean Project” option after the clean process finishes then select “Rebuild Project” option and let it be complete .

      Hope this may help you , Feel free to ask 🙂

      Thanks

      • Arij

        still not working ! please help ! having the same problem

  • Mega Ness

    Hi admin .. I want to work another table I store new information and keep it for the same application I mean at the beginning is logged in and after that records other information and presents it but I am a beginner and do not know I do more than a table in the database itself I want to teach me to do two tables, please

    I’ve worked on another rule and a new table for the same application but I did not save the message message Unfortunately, My Application has stopped

    Please help me

    • Admin

      Hello Mega,

      The class that extends SQLiteOpenHelper in that class we overide the onCreate funtion
      like below:-
      @Override
      public void onCreate(SQLiteDatabase db) {

      }

      In this function we write the SQL query to create table , so we can also create multiple tables over here like :-
      @Override
      public void onCreate(SQLiteDatabase db) {
      db.execSQL(CREATE_USER_TABLE);
      db.execSQL(CREATE_INFORMATION_TABLE);
      }

      and to perform CRUD operation you have to write functions like i have created in DatabaseHelper class by changing the table name ,columns name and define the modal class also.

      Hope this may help you , Feel free to ask 🙂

      Thanks

      • Mega Ness

        I am a newbie in this program but a graduate project that I do apply reservation booking is required to do my schedule
        To sign in and book
        I am limited in time to accomplish it ….
        Like this you mean
        Public class DATABASE extends SQLiteOpenHelper {

        Public static final String DATABASE_NAME = “Airways_database.db”;
        Public static final String TABLE_NAME1 = “User_table.db”;
        Public static final String COL_1 = “ID”;
        Public static final String COL_2 = “FirstName”;
        Public static final String COL_4 = “LastName”;
        Public static final String COL_5 = “Email”;
        Public static final String COL_6 = “Password”;
        Public static final String COL_8 = “DateofBirth”;
        Public static final String COL_9 = “Number phone”;
        Public static final String COL_10 = “Address”;
        Public static final String COL_11 = “City”;
        Public static final String COL_12 = “Area”;
        Public static final String COL_13 = “Country”;
        Public static final String TABLE_NAME2 = “Booker_table.db”;
        Public static final String COL_14 = “Typetrip”;
        Public static final String COL_15 = “From”;
        Public static final String COL_16 = “To”;
        Public static final String COL_17 = “Departure”;
        Public static final String COL_18 = “Return”;
        Public static final String COL_19 = “Class”;
        Public static final String COL_20 = “Adult”;
        Public static final String COL_21 = “Child”;
        Public static final String COL_22 = “Infant”;
        Public static final String COL_24 = “Time”;

        Public DATABASE (Context context) {
        Super (context, DATABASE_NAME, null, 1);

        }

        @Override
        Public void onCreate (SQLiteDatabase db) {
        Db.execSQL (“create table” + TABLE_NAME1 + “(ID INTEGER PRIMARY KEY AUTOINCREMENT, TEXT FirstName,” +
        “LastName TEXT, Email TEXT, Password TEXT, DateofBirth DATETIME, Number phone INTEGER, Address TEXT, City TEXT” +
        “Area TEXT, Country TEXT”);
        Db.execSQL (“create table” + TABLE_NAME2 + “(Typetrip TEXT, From TEXT, To TEXT, Departure TEXT, Return TEXT,” +
        “Class TEXT, Adult INTEGER, Child INTEGER, Infant INTEGER, Time TEXT)”);
        }

        • Admin

          Yes this i mean. so are you facing any problem in it.

  • Mohd Shahdan Bin Addenan

    hi admin…I leverage your code to create another table..but it seems the table only can accept max 4 column (item_id, asset_number, asset_desc, asset_cal_desc)..when I tried to add all column (totall 10 column including item_id, make project success, but app crash when tried to view the StoreViewActivity.java (similar to UsersListActivity.java function). If I disable those 6 column & left the 1st 4 column, the StoreViewActivity.java is running fine. Kindly review my code & advise what might be my mistake.

    • Mohd Shahdan Bin Addenan

      DatabaseHelperInventory.java

      package com.androidtutorialshub.loginregister.sql;

      import android.content.ContentValues;
      import android.content.Context;
      import android.database.Cursor;
      import android.database.sqlite.SQLiteDatabase;
      import android.database.sqlite.SQLiteOpenHelper;

      import com.androidtutorialshub.loginregister.model.Item;

      import java.util.ArrayList;
      import java.util.List;

      /**
      * Created by Mohd Shahdan Addenan on 9/12/2016.
      */
      public class DatabaseHelperInventory extends SQLiteOpenHelper {

      // Database Version
      private static final int DATABASE_VERSION = 1;

      // Database Name
      private static final String DATABASE_NAME = “AssetManager.db”;

      // Item table name
      private static final String TABLE_ITEM = “item”;

      // Item Table Columns names
      private static final String COLUMN_ITEM_ID = “item_id”;
      private static final String COLUMN_ASSET_NUMBER = “asset_number”;
      private static final String COLUMN_ASSET_DESC = “asset_desc”;
      private static final String COLUMN_ASSET_CAL_DESC = “asset_cal_desc”;
      private static final String COLUMN_ASSET_LOC = “asset_loc”;
      private static final String COLUMN_CAL_DATE = “cal_date”;
      private static final String COLUMN_CAL_DUE = “cal_due”;
      private static final String COLUMN_USER_GROUP = “user_group”;
      private static final String COLUMN_USAGE = “usage”;
      private static final String COLUMN_USER = “user”;

      // create table sql query
      private String CREATE_ITEM_TABLE = “CREATE TABLE ” + TABLE_ITEM + “(”
      + COLUMN_ITEM_ID + ” INTEGER PRIMARY KEY AUTOINCREMENT,” + COLUMN_ASSET_NUMBER + ” TEXT,”
      + COLUMN_ASSET_DESC + ” TEXT,” + COLUMN_ASSET_CAL_DESC + ” TEXT,”
      + COLUMN_ASSET_LOC + ” TEXT,” + COLUMN_CAL_DATE + ” TEXT,” + COLUMN_CAL_DUE + ” TEXT,”
      + COLUMN_USER_GROUP + ” TEXT,” + COLUMN_USAGE + ” TEXT,” + COLUMN_USER + ” TEXT ” + “)”;

      // drop table sql query
      private String DROP_ITEM_TABLE = “DROP TABLE IF EXISTS ” + TABLE_ITEM;

      /**
      * Constructor
      *
      * @param context
      */
      public DatabaseHelperInventory(Context context) {
      super(context, DATABASE_NAME, null, DATABASE_VERSION);
      }

      @Override
      public void onCreate(SQLiteDatabase db) {
      db.execSQL(CREATE_ITEM_TABLE);
      }

      @Override
      public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

      //Drop Item Table if exist
      db.execSQL(DROP_ITEM_TABLE);

      // Create tables again
      onCreate(db);

      }

      /**
      * This method is to create item record
      *
      * @param item
      */
      public void addItem(Item item) {
      SQLiteDatabase db = this.getWritableDatabase();

      ContentValues values = new ContentValues();
      values.put(COLUMN_ASSET_NUMBER, item.getAsset_number());
      values.put(COLUMN_ASSET_DESC, item.getAsset_desc());
      values.put(COLUMN_ASSET_CAL_DESC, item.getAsset_cal_desc());
      //values.put(COLUMN_ASSET_LOC, item.getAsset_loc());
      // values.put(COLUMN_CAL_DATE, item.getCal_date());
      //values.put(COLUMN_CAL_DUE, item.getCal_due());
      // values.put(COLUMN_USER_GROUP, item.getUser_group());
      // values.put(COLUMN_USAGE, item.getUsage());
      // values.put(COLUMN_USER, item.getUser());

      // Inserting Row
      db.insert(TABLE_ITEM, null, values);
      db.close();
      }

      /**
      * This method is to fetch all item and return the list of item records
      *
      * @return list
      */
      public List getAllItem() {
      // array of columns to fetch
      String[] columns = {
      COLUMN_ITEM_ID,
      COLUMN_ASSET_NUMBER,
      COLUMN_ASSET_DESC,
      COLUMN_ASSET_CAL_DESC
      //COLUMN_ASSET_LOC,
      //COLUMN_CAL_DATE,
      //COLUMN_CAL_DUE,
      //COLUMN_USER_GROUP,
      //COLUMN_USAGE,
      //COLUMN_USER

      };
      // sorting orders
      String sortOrder =
      COLUMN_ASSET_DESC + ” ASC”;
      List itemList = new ArrayList();

      SQLiteDatabase db = this.getReadableDatabase();

      // query the item table
      /**
      * Here query function is used to fetch records from item table this function works like we use sql query.
      * SQL query equivalent to this query function is
      * SELECT item_id,asset_number,asset_desc,asset_cal_desc FROM item ORDER BY asset_number;
      */
      Cursor cursor = db.query(TABLE_ITEM, //Table to query
      columns, //columns to return
      null, //columns for the WHERE clause
      null, //The values for the WHERE clause
      null, //group the rows
      null, //filter by row groups
      sortOrder); //The sort order

      // Traversing through all rows and adding to list
      if (cursor.moveToFirst()) {
      do {
      Item item = new Item();
      item.setId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(COLUMN_ITEM_ID))));
      item.setAsset_number(cursor.getString(cursor.getColumnIndex(COLUMN_ASSET_NUMBER)));
      item.setAsset_desc(cursor.getString(cursor.getColumnIndex(COLUMN_ASSET_DESC)));
      item.setAsset_cal_desc(cursor.getString(cursor.getColumnIndex(COLUMN_ASSET_CAL_DESC)));
      // item.setAsset_loc(cursor.getString(cursor.getColumnIndex(COLUMN_ASSET_LOC)));
      // item.setCal_date(cursor.getString(cursor.getColumnIndex(COLUMN_CAL_DATE)));
      // item.setCal_due(cursor.getString(cursor.getColumnIndex(COLUMN_CAL_DUE)));
      // item.setUser_group(cursor.getString(cursor.getColumnIndex(COLUMN_USER_GROUP)));
      // item.setUsage(cursor.getString(cursor.getColumnIndex(COLUMN_USAGE)));
      // item.setUser(cursor.getString(cursor.getColumnIndex(COLUMN_USER)));

      // Adding item record to list
      itemList.add(item);
      } while (cursor.moveToNext());
      }
      cursor.close();
      db.close();

      // return item list
      return itemList;
      }

      /**
      * This method to update item record
      *
      * @param item
      */
      public void updateItem(Item item) {
      SQLiteDatabase db = this.getWritableDatabase();

      ContentValues values = new ContentValues();
      values.put(COLUMN_ASSET_NUMBER, item.getAsset_number());
      values.put(COLUMN_ASSET_DESC, item.getAsset_desc());
      values.put(COLUMN_ASSET_CAL_DESC, item.getAsset_cal_desc());
      //values.put(COLUMN_ASSET_LOC, item.getAsset_loc());
      //values.put(COLUMN_CAL_DATE, item.getCal_date());
      //values.put(COLUMN_CAL_DUE, item.getCal_due());
      // values.put(COLUMN_USER_GROUP, item.getUser_group());
      // values.put(COLUMN_USAGE, item.getUsage());
      // values.put(COLUMN_USER, item.getUser());

      // updating row
      db.update(TABLE_ITEM, values, COLUMN_ITEM_ID + ” = ?”,
      new String[]{String.valueOf(item.getId())});
      db.close();
      }

      /**
      * This method is to delete item record
      *
      * @param item
      */
      public void deleteItem(Item item) {
      SQLiteDatabase db = this.getWritableDatabase();
      // delete item record by id
      db.delete(TABLE_ITEM, COLUMN_ITEM_ID + ” = ?”,
      new String[]{String.valueOf(item.getId())});
      db.close();
      }

      /**
      * This method to check item exist or not
      *
      * @param asset_number
      * @return true/false
      */
      public boolean checkItem(String asset_number) {

      // array of columns to fetch
      String[] columns = {
      COLUMN_ITEM_ID
      };
      SQLiteDatabase db = this.getReadableDatabase();

      // selection criteria
      String selection = COLUMN_ASSET_NUMBER + ” = ?”;

      // selection argument
      String[] selectionArgs = {asset_number};

      // query item table with condition
      /**
      * Here query function is used to fetch records from item table this function works like we use sql query.
      * SQL query equivalent to this query function is
      * SELECT item_id FROM user WHERE asset_desc = ‘jack@androidtutorialshub.com’;
      */
      Cursor cursor = db.query(TABLE_ITEM, //Table to query
      columns, //columns to return
      selection, //columns for the WHERE clause
      selectionArgs, //The values for the WHERE clause
      null, //group the rows
      null, //filter by row groups
      null); //The sort order
      int cursorCount = cursor.getCount();
      cursor.close();
      db.close();

      if (cursorCount > 0) {
      return true;
      }

      return false;
      }

      /**
      * This method to check item exist or not by checking asset number vs asset desc
      *
      * @param asset_number
      * @param asset_desc
      * @return true/false
      */
      public boolean checkItem(String asset_number, String asset_desc) {

      // array of columns to fetch
      String[] columns = {
      COLUMN_ITEM_ID
      };
      SQLiteDatabase db = this.getReadableDatabase();
      // selection criteria
      String selection = COLUMN_ASSET_NUMBER + ” = ?” + ” AND ” + COLUMN_ASSET_DESC + ” = ?”;

      // selection arguments
      String[] selectionArgs = {asset_number, asset_desc};

      // query user table with conditions
      /**
      * Here query function is used to fetch records from user table this function works like we use sql query.
      * SQL query equivalent to this query function is
      * SELECT user_id FROM user WHERE user_email = ‘jack@androidtutorialshub.com’ AND user_password = ‘qwerty’;
      */
      Cursor cursor = db.query(TABLE_ITEM, //Table to query
      columns, //columns to return
      selection, //columns for the WHERE clause
      selectionArgs, //The values for the WHERE clause
      null, //group the rows
      null, //filter by row groups
      null); //The sort order

      int cursorCount = cursor.getCount();

      cursor.close();
      db.close();
      if (cursorCount > 0) {
      return true;
      }

      return false;
      }

      }

      • Mohd Shahdan Bin Addenan

        Item.java (model)

        package com.androidtutorialshub.loginregister.model;

        /**
        * Created by Mohd Shahdan Addenan on 9/12/2016.
        */
        public class Item {

        private int id;
        private String asset_number;
        private String asset_desc;
        private String asset_cal_desc;
        //private String asset_loc;
        //private String cal_date;
        //private String cal_due;
        // private String user_group;
        //private String usage;
        //private String user;

        public int getId() { return id; }
        public void setId(int id) { this.id = id; }

        public String getAsset_number() { return asset_number; }
        public void setAsset_number(String asset_number) {this.asset_number = asset_number;}

        public String getAsset_desc() { return asset_desc; }
        public void setAsset_desc(String asset_desc) {this.asset_desc = asset_desc;}

        public String getAsset_cal_desc() { return asset_cal_desc; }
        public void setAsset_cal_desc(String asset_cal_desc) {this.asset_cal_desc = asset_cal_desc;}

        //public String getAsset_loc() { return asset_loc; }
        //public void setAsset_loc(String asset_loc) {this.asset_loc = asset_loc;}

        // public String getCal_date() { return cal_date; }
        // public void setCal_date(String cal_date) {this.cal_date = cal_date;}

        //public String getCal_due() { return cal_due; }
        //public void setCal_due(String cal_due) {this.cal_due = cal_due;}

        // public String getUser_group() { return user_group; }
        //public void setUser_group(String user_group) {this.user_group = user_group;}

        // public String getUsage() { return usage; }
        // public void setUsage(String usage) {this.usage = usage;}

        //public String getUser() { return user; }
        //public void setUser(String user) {this.user = user;}

        }

        • Mohd Shahdan Bin Addenan

          StoreViewActivity.java (activities)

          package com.androidtutorialshub.loginregister.activities;

          import android.content.Intent;
          import android.os.AsyncTask;
          import android.os.Bundle;
          import android.support.annotation.Nullable;
          import android.support.v7.app.AppCompatActivity;
          import android.support.v7.widget.AppCompatTextView;
          import android.support.v7.widget.DefaultItemAnimator;
          import android.support.v7.widget.LinearLayoutManager;
          import android.support.v7.widget.RecyclerView;
          import android.view.View;
          import android.widget.Button;
          import android.widget.Toast;

          import com.androidtutorialshub.loginregister.R;
          import com.androidtutorialshub.loginregister.adapters.ItemsRecyclerAdapter;
          import com.androidtutorialshub.loginregister.model.Item;
          import com.androidtutorialshub.loginregister.sql.DatabaseHelperInventory;

          import java.util.ArrayList;
          import java.util.List;

          /**
          * Created by Mohd Shahdan Addenan on 10/10/2016.
          */

          public class StoreViewActivity extends AppCompatActivity {
          Button btnAddInventory;
          Button btnAdmin;

          private AppCompatActivity activity = StoreViewActivity.this;
          private AppCompatTextView textViewAssetNum;
          //private AppCompatTextView textViewAssetDesc;
          //private AppCompatTextView textViewAssetCalDesc;
          //private AppCompatTextView textViewAssetLoc;
          //private AppCompatTextView textViewCalDate;
          //private AppCompatTextView textViewCalDue;
          //private AppCompatTextView textViewUserGroup;
          //private AppCompatTextView textViewUsage;
          //private AppCompatTextView textViewUser;
          //private AppCompatTextView textViewName;

          private RecyclerView recyclerViewItems;
          private List listItems;
          private ItemsRecyclerAdapter itemsRecyclerAdapter;
          private DatabaseHelperInventory databaseHelper;

          @Override
          protected void onCreate(@Nullable Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_store_view);
          getSupportActionBar().setTitle(“”);
          initViews();
          initObjects();
          // Locate the button in activity_users_list.xml
          btnAddInventory = (Button)findViewById(R.id.buttonAdd);
          btnAdmin = (Button)findViewById(R.id.buttonAdmin);

          }

          // Capture button clicks
          public void sendMessage(View view)
          {
          Intent intentadd = new Intent(StoreViewActivity.this, StoreAddActivity.class);
          startActivity(intentadd);
          Toast.makeText(StoreViewActivity.this,”Going to add items into Inventory Database”, Toast.LENGTH_LONG).show();

          }
          // Capture button clicks
          public void sendMessage1(View view)
          {
          Intent intentadmin = new Intent(StoreViewActivity.this, UsersListActivity.class);
          startActivity(intentadmin);
          Toast.makeText(StoreViewActivity.this,”Going back to Admin account”, Toast.LENGTH_LONG).show();
          }

          /**
          * This method is to initialize views
          */
          private void initViews() {
          textViewAssetNum = (AppCompatTextView) findViewById(R.id.textViewAssetNum);
          recyclerViewItems = (RecyclerView) findViewById(R.id.recyclerViewItems);
          }

          /**
          * This method is to initialize objects to be used
          */
          private void initObjects() {
          listItems = new ArrayList();
          itemsRecyclerAdapter = new ItemsRecyclerAdapter(listItems);

          RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
          recyclerViewItems.setLayoutManager(mLayoutManager);
          recyclerViewItems.setItemAnimator(new DefaultItemAnimator());
          recyclerViewItems.setHasFixedSize(true);
          recyclerViewItems.setAdapter(itemsRecyclerAdapter);
          databaseHelper = new DatabaseHelperInventory(activity);

          //String emailFromIntent = getIntent().getStringExtra(“EMAIL”);
          //textViewName.setText(emailFromIntent);

          getDataFromSQLite();
          }

          /**
          * This method is to fetch all item records from SQLite
          */
          private void getDataFromSQLite() {
          // AsyncTask is used that SQLite operation not blocks the UI Thread.
          new AsyncTask() {
          @Override
          protected Void doInBackground(Void… params) {
          listItems.clear();
          listItems.addAll(databaseHelper.getAllItem());

          return null;
          }

          @Override
          protected void onPostExecute(Void aVoid) {
          super.onPostExecute(aVoid);
          itemsRecyclerAdapter.notifyDataSetChanged();
          }
          }.execute();
          }
          }

  • Mohd Shahdan Bin Addenan

    hi..anyone using this apps code & manage to enable delete & update function using RecyclerViewClickListener + RecyclerViewTouchListener?? I’m still stuck to enable those function..help needed to share your code – thanks in advance 🙂

    • Mohd Shahdan Bin Addenan

      this is what I’ve done yesterday, but still stuck with multiple error..

      ItemRecyclerViewTouchListener.java

      package com.androidtutorialshub.loginregister.helpers;

      import android.content.Context;
      import android.support.v7.widget.RecyclerView;
      import android.view.GestureDetector;
      import android.view.MotionEvent;
      import android.view.View;

      /**
      * Created by maddenan on 5/7/2017.
      */

      public class ItemRecyclerViewTouchListener implements RecyclerView.OnItemTouchListener {
      private GestureDetector gestureDetector;
      private ItemRecyclerViewTouchListener clickListener;

      public ItemRecyclerViewTouchListener(Context context, final RecyclerView recyclerView, final ItemRecyclerViewTouchListener clickListener) {
      this.clickListener = clickListener;
      gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
      @Override
      public boolean onSingleTapUp(MotionEvent e) {
      return true;
      }

      @Override
      public void onLongPress(MotionEvent e) {
      View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
      if (child != null && clickListener != null) {
      clickListener.onLongClick(child, recyclerView.getChildPosition(child));
      }
      }
      });
      }

      @Override
      public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {

      View child = rv.findChildViewUnder(e.getX(), e.getY());
      if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
      clickListener.onClick(child, rv.getChildPosition(child));
      }
      return false;
      }

      @Override
      public void onTouchEvent(RecyclerView rv, MotionEvent e) {
      }

      @Override
      public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

      }
      }

      • Mohd Shahdan Bin Addenan

        ItemRecyclerViewClickListener.java

        package com.androidtutorialshub.loginregister.helpers;

        import android.view.View;

        /**
        * Created by Mohd Shahdan Addenan on 5/7/2017.
        */
        public interface ItemRecyclerViewClickListener {
        void onClick(View view, int position);
        void onLongClick(View view, int position);

        }

        • Mohd Shahdan Bin Addenan

          StoreViewActivity.java (activities) , still stuck with errors after tried to enable those RecycleViewer click listener in order to enable delete & update function for StoreViewActivity.java

          package com.androidtutorialshub.loginregister.activities;

          import android.content.Intent;
          import android.os.AsyncTask;
          import android.os.Bundle;
          import android.support.annotation.Nullable;
          import android.support.v7.app.AppCompatActivity;
          import android.support.v7.widget.AppCompatTextView;
          import android.support.v7.widget.DefaultItemAnimator;
          import android.support.v7.widget.LinearLayoutManager;
          import android.support.v7.widget.RecyclerView;
          import android.view.View;
          import android.widget.Button;
          import android.widget.Toast;

          import com.androidtutorialshub.loginregister.R;
          import com.androidtutorialshub.loginregister.adapters.ItemsRecyclerAdapter;
          import com.androidtutorialshub.loginregister.model.Item;
          import com.androidtutorialshub.loginregister.sql.DatabaseHelperInventory;

          import java.util.ArrayList;
          import java.util.List;

          /**
          * Created by Mohd Shahdan Addenan on 10/10/2016.
          */

          public class StoreViewActivity extends AppCompatActivity {

          Button btnAddInventory;
          Button btnAdmin;

          private AppCompatActivity activity = StoreViewActivity.this;
          private AppCompatTextView textViewAssetNum;
          //private AppCompatTextView textViewAssetDesc;
          //private AppCompatTextView textViewAssetCalDesc;
          //private AppCompatTextView textViewAssetLoc;
          //private AppCompatTextView textViewCalDate;
          //private AppCompatTextView textViewCalDue;
          //private AppCompatTextView textViewUserGroup;
          //private AppCompatTextView textViewUsage;
          //private AppCompatTextView textViewUser;
          //private AppCompatTextView textViewName;

          private RecyclerView recyclerViewItems;
          private List listItems;
          private ItemsRecyclerAdapter itemsRecyclerAdapter;
          private DatabaseHelperInventory databaseHelper;

          recyclerViewItems.addOnItemTouchListener(new RecyclerViewTouchListener(getApplicationContext(), recyclerView, new RecyclerViewClickListener() {
          @Override
          public void onClick(View view, int position) {
          Toast.makeText(getApplicationContext(), listItems.get(position).getAsset_number() + ” is clicked!”, Toast.LENGTH_SHORT).show();
          }

          @Override
          public void onLongClick(View view, int position) {
          Toast.makeText(getApplicationContext(), listItems.get(position).getAsset_number() + ” is long pressed!”, Toast.LENGTH_SHORT).show();

          }
          }));

          @Override
          protected void onCreate(@Nullable Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_store_view);
          getSupportActionBar().setTitle(“”);

          initViews();
          initObjects();
          // Locate the button in activity_users_list.xml
          btnAddInventory = (Button)findViewById(R.id.buttonAdd);
          btnAdmin = (Button)findViewById(R.id.buttonAdmin);

          }

          // Capture button clicks
          public void sendMessage(View view)
          {
          Intent intentadd = new Intent(StoreViewActivity.this, StoreAddActivity.class);
          startActivity(intentadd);
          Toast.makeText(StoreViewActivity.this,”Going to add items into Inventory Database”, Toast.LENGTH_LONG).show();

          }
          // Capture button clicks
          public void sendMessage1(View view)
          {
          Intent intentadmin = new Intent(StoreViewActivity.this, UsersListActivity.class);
          startActivity(intentadmin);
          Toast.makeText(StoreViewActivity.this,”Going back to Admin account”, Toast.LENGTH_LONG).show();
          }

          /**
          * This method is to initialize views
          */
          private void initViews() {
          textViewAssetNum = (AppCompatTextView) findViewById(R.id.textViewAssetNum);
          recyclerViewItems = (RecyclerView) findViewById(R.id.recyclerViewItems);
          }

          /**
          * This method is to initialize objects to be used
          */
          private void initObjects() {
          listItems = new ArrayList();
          itemsRecyclerAdapter = new ItemsRecyclerAdapter(listItems);

          RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
          recyclerViewItems.setLayoutManager(mLayoutManager);
          recyclerViewItems.setItemAnimator(new DefaultItemAnimator());
          recyclerViewItems.setHasFixedSize(true);
          recyclerViewItems.setAdapter(itemsRecyclerAdapter);
          databaseHelper = new DatabaseHelperInventory(activity);

          //String emailFromIntent = getIntent().getStringExtra(“EMAIL”);
          //textViewName.setText(emailFromIntent);

          getDataFromSQLite();
          }

          /**
          * This method is to fetch all item records from SQLite
          */
          private void getDataFromSQLite() {
          // AsyncTask is used that SQLite operation not blocks the UI Thread.
          new AsyncTask() {
          @Override
          protected Void doInBackground(Void… params) {
          listItems.clear();
          listItems.addAll(databaseHelper.getAllItem());

          return null;
          }

          @Override
          protected void onPostExecute(Void aVoid) {
          super.onPostExecute(aVoid);
          itemsRecyclerAdapter.notifyDataSetChanged();
          }
          }.execute();
          }
          }

  • surendra

    Hi where can i find the saved user details in database as a folder in the project

  • Andrés Felipe Contreras Muñoz

    gracias por tu excelente tutorial….

    • Admin

      Thanks Andrés 🙂

  • Wendy

    Hi admin, how can you modify the login/ register activity with SQLiteAssetHeper with existing table in assets? Can we still use the same method as SQLOpenHelper method?

  • Akash Soni

    hello i have login data show another activity means user profile plz suggest

    • Lalit Vasan

      Hi Akash,

      Just query the database with user id to get all details on profile screen.

      Hope this may help you , Feel free to ask 🙂

      Thanks

  • Yohanes Agung Sasono

    Great Tutorial, Thx a lot.
    works like charm 🙂

    • Admin

      Welcome Yohanes Agung Sasono 🙂

  • MD HASNAIN

    hi admin when i’m trying to run the app its is showing default activity not found

    • Admin

      Hi MD Hasnain,

      Can you share the logs for the error.

      Hope this may help you , Feel free to ask 🙂

      Thanks

  • Paco Paco

    that was a really nice article it helped me a lot
    I want to use it for a small proyect for school but I need to add a new activity with a basic overlay when I press Log In, how is it possible with your code? To start like a standart activity with a menu and a normal layout

    • Admin

      Hi Paco,

      you have to change activity launched after login process.

      Code in Login Activity in verifyFromSQLite():-

      Intent accountsIntent = new Intent(activity, UsersListActivity.class); // change over here for the activity you need.
      accountsIntent.putExtra(“EMAIL”, textInputEditTextEmail.getText().toString().trim());
      emptyInputEditText();
      startActivity(accountsIntent);

      Hope this may help you , Feel free to ask 🙂

      Thanks

      • Jaya Mahesh Prathipati

        after i changed to main activity its throwing an error unfortunately app has stopped

        • Chris Brown

          you figure it out? I managed to in a couple minutes(learning as well). here’s how i did it.

          – Open LoginActivity.class(activity).

          – Scroll to this section:

          Intent accountsIntent = new Intent(activity, UsersListActivity.class);
          accountsIntent.putExtra(“EMAIL”, textInputEditTextEmail.getText().toString().trim());
          emptyInputEditText();
          startActivity(accountsIntent);

          – Then, Comment all that out like this example:

          //Intent accountsIntent = new Intent(activity, UsersListActivity.class);
          //accountsIntent.putExtra(“EMAIL”,
          textInputEditTextEmail.getText().toString().trim());
          //emptyInputEditText();
          //startActivity(accountsIntent);

          – Then Paste in his Example code Snippet EXACTLY above or below that SIMILAR commented out code.

          – Then, focus on this line you pasted in:

          Intent accountsIntent = new Intent(activity, UsersListActivity.class);

          – Change UsersListActivity to MainScreenActivity or the name of the Java/XML you want it to open.

          – Your code will look like this:

          //Intent accountsIntent = new Intent(activity, UsersListActivity.class);
          //accountsIntent.putExtra(“EMAIL”, textInputEditTextEmail.getText().toString().trim());
          //emptyInputEditText();
          //startActivity(accountsIntent);

          Intent accountsIntent = new Intent(activity, MainScreenActivity.class); // change over here for the activity you need.
          accountsIntent.putExtra(“EMAIL”, textInputEditTextEmail.getText().toString().trim());
          emptyInputEditText();
          startActivity(accountsIntent);

          – Then, go to the menu bar and then Choose ‘Clean Project’, Then ‘Build Project’

          – Bam! It works. Your Pro. ????. Profit.

          Congratz.

          • Admin

            Great man.

          • kranthi a

            no its not working can u please elaborate it

          • Josh Tagz Benong

            i solve this issue when i put my second activity to my android manifest like this one..

          • Josh Tagz Benong

            you just edit Users.ListActivity.class into MainScreenActivity.class sir, it’s not working it just the same as Admin Mod… its not working sir. Always saying, “Unfortunately, your application has stopped.

        • kranthi a

          iam also getting the same error can u please tell me how to rectifie it

  • Kishan

    Hello admin,Your article are superb and really helped me.But one error still in my project i.e. setErrorEnabled(false) actually my error message not showing when I set setError(null) at the place of setErrorEnabled(false),I want error message .Please solve this my issue.

  • Jaya Mahesh Prathipati

    can you please explain session manager.
    once i exit from app again its asking for login credentials it’s irritate the user so please explain about session manager and hoe to use in this code?

    Or please explain how to use SharedPreferences in your existing code

    • Admin

      Hi Jaya,

      You have to maintain session for that by using shared preferences . Follow the steps below to achieve your requirements:-
      1) After successfull login store one key for session and id of user in shared preferences.
      2) Now create one more activity i.e welcome activity create a check using shared preferences that user is logged in or not, if logged in then redirect to main screen or take it to login screen.
      3) To show information of user on main screen use ID of user stored in shared preferences to fetch users data from SQLite.

      Hope this may help you , Feel free to ask 🙂

      Thanks

  • Prerna Chawla

    Whenever I click on register button my app crashes…I have also removed the setErrorEnabled(true); in my inputvalidation file…

  • Aya

    hey admin , thanks for your effort.
    Your code helped me a lot with my school project. but i got one problem .I’m trying to use the recyclerAdapter with another example and it’s showing just the first ‘user’ in your code’s case. what should i do?

    • Admin

      Hi Aya,

      Can you post the code that you are using .

      Thanks

  • Lingesh Waran

    Hi admin , i managed to compile your code , without any error. But my app closes immediately after opening. Can yo help me to resolve it.

    • Admin

      Hi Lingesh,

      Yes i can help you but please post the crash logs.

      Thanks

  • Pate Ortega

    Hello admin! I just want to ask, how will I use the code in viewing all the data in a fragment? Thank you!!!

    • Admin

      Hi Pate,

      It is same like i have done in activity.

      Hope this may help you , Feel free to ask 🙂

      Thanks

      • Pate Ortega

        I have done it but everytime I view it, my app gets into a force close. How can I fix it?

  • Em

    hi admin. i was able to get your code to run in my laptop. I need help on how can i delete and update a user. Can you help me because i don’t know how to use the methods that you defined in the databasehelper class. thanks in advance

  • Pate Ortega

    hi! How will I display the data of a specific or current user log in in my app and also a user can edit their data? thank you!!

    • Admin

      Hi Pate,

      You can do it by the using following approaches:-

      Approach 1 :-
      First check user credentials by querying to SQLite, if user exist query will return full user record. Save the full record in shared preferences and now you can display details on any activity by fetching record from shared preferences.

      Approach 2 :-
      First check user credentials by querying to SQLite, if user exist query will return id of the user. Save the id in shared preferences and now you can display details on any activity by fetching record from id stored in shared preferences.

      Hope this may help you , Feel free to ask 🙂

      Thanks

      • Pate Ortega

        Got it. Thank you!!!

      • balboy

        Dear Sir, I unable to fetch user id and store it inside shared preferences but I able to store email through textInputEditTextEmail.getText().toString().trim(). so far i stuck on fetching user id and store it inside shared pref. Pls Help n tq for awesome tutorial

        • Admin

          Hi BalBoy,

          you have to create a function in DatabaseHelper Class which will return the users data against login credentials.

          Hope this may help you , Feel free to ask 🙂

          Thanks

  • ADITYA RANA

    if (databaseHelper.checkUser(textInputEditTextEmail.getText().toString().trim()
    , textInputEditTextPassword.getText().toString().trim())) {

    Intent accountsIntent = new Intent(activity, UsersListActivity.class);
    accountsIntent.putExtra(“EMAIL”, textInputEditTextEmail.getText().toString().trim());
    emptyInputEditText();
    startActivity(accountsIntent);

    } else {
    // Snack Bar to show success message that record is wrong
    Snackbar.make(nestedScrollView, getString(R.string.error_valid_email_password), Snackbar.LENGTH_LONG).show();
    }

    how do i do changes to this if statement …to check…if the email id=abs@gmail.com and password=**** becomes true then only the if statement executes….

    • Admin

      if( textInputEditTextEmail.getText().toString().trim().equals(“abs@gmail.com”) && textInputEditTextPassword.getText().toString().trim().equals(“*****”)){

      // code for if statement is true.

      }else{

      // code for if statement is false.

      }

      Hope this may help you , Feel free to ask 🙂

      Thanks

  • Christopher Sheridan

    Hello. I am trying to Register and then Log In. I commented out all of the setErrorEnabled(false) statements per the suggestions from other comments in this thread. That did not work. The app would crash upon clicking Register.
    Next, I added a try/catch in the DatabaseHelper class at this section:

    try {
    Cursor cursor = db.query(TABLE_USER, //Table to query
    columns, //columns to return
    selection, //columns for the WHERE clause
    selectionArgs, //The values for the WHERE clause
    null, //group the rows
    null, //filter by row groups
    null); //The sort order
    int cursorCount = cursor.getCount();
    cursor.close();
    db.close();

    if (cursorCount > 0) {
    return true;
    }
    } catch(Exception e) {
    Log.d(TAG, “db.query”, e);

    }

    return false;
    }

    I was able to Register after that, at least I thought. The data folder is empty when I inspect the File Explorer in Android Device Monitor.

    Without the try/catch, I get an SQLiteException: no such column user_email while compiling: SELECT user_id FROM user WHERE user_email = ?

    The app is crashing after button click, and I can’t seem to figure out why.

  • ag. azlee

    Hello admin.. thank you for this tutorial..its great..
    how to create Logout to this app? and how to use volley to store sqlite data to server mysql for backup?

    • Lalit Vasan

      Hi Azlee,

      Use shared preferences to do this task. first store the user data in shared preferences and then for log out clear the preferences. Follow this url for shared preferences :- http://www.androidtutorialshub.com/android-shared-preferences-tutorial/

      To store data to server you have to call web-service for calling webservice you can use simple http or any third party library like retrofit or volley . Follow this url for volley :- http://www.androidtutorialshub.com/android-working-with-volley-library-http-get-post-put-delete-request/

      Hope this may help you , Feel free to ask 🙂

      Thanks

      • Hassan Ali Mughal

        Hello Admin thank you for this tutorial..its great
        In this tutorial i adding the extra data, the programm is excute the hregistration is successfully but in login i put the correct email ur password but programm siad the wrong email or password kindly tell me the solution

  • Tha Nesh

    how to get only user account in UsersListActivity class.. if any body have any idea plz help me .

    • Admin

      Hi Tha Nesh,

      You can do it by the using following approaches:-

      Approach 1 :-
      First check user credentials by querying to SQLite, if user exist query will return full user record. Save the full record in shared preferences and now you can display details on any activity by fetching record from shared preferences.

      Approach 2 :-
      First check user credentials by querying to SQLite, if user exist query will return id of the user. Save the id in shared preferences and now you can display details on any activity by fetching record from id stored in shared preferences.

      Hope this may help you , Feel free to ask 🙂

      Thanks

  • Rawat

    plz also explain how to use update and delete users..

  • Ridhima joshi

    Only the first record gets displayed. The code is the same.

  • user12345

    Thank you for sharing this.

    How can we hide the passwords displayed?

    Please reply asap.
    Thank you.

    • Lalit Vasan

      Hi user,

      To hide password in edit text user you can user attribute android:inputType=”textPassword” or android:password=”true”

      Hope this may help you , Feel free to ask 🙂

      Thanks

  • Slice Cut

    for update and delete name email address and passsword at once, post the full code for it , dont comment the half code plz Thanks in advance

    • Lalit Vasan

      Hi Slice

      Kindly check the DatabaseHelper class mentioned above there is method to update and delete with name updateUser(User user) and deleteUser(User user) . Just call this methods by passing user object it will update and delete user accordingly.

      Hope this may help you , Feel free to ask 🙂

      Thanks

  • Josh Tagz Benong

    How to put another activities sir with this kind of login and register with sqlite database…
    i look for the answer on google but it hard to put another intent with the existing lots of intent with this activities

    • Lalit Vasan

      Hi Josh,

      Can you please elaborate you problem so that i can give you correct answer.

      Thanks

  • Mohammad Ali Kadiwala

    hey admin can u teach me
    how to i get data from registration page in my profile fragment
    not all data only each data show which email or password to i login

    • Lalit Vasan

      Hi Ali,

      You can use intent’s putExtra() getExtra() methods to do this task OR you can use shared preferences to store data and display on profile fragment.

      Hope this may help you , Feel free to ask 🙂

      Thanks

      • Mohammad Ali Kadiwala

        I already complete this task Using PutExtra() or getExtra()
        Thank you for your Reply 🙂

  • Irfan Ahmed

    excellent tutorial on connecting to sqllite db.

    where is the default location for “UserManager.db”, where is it stored , how topack and export with apk ?

    • Admin

      Hi Irfan,

      Database files are stored in path “/data/data/[your_package_name]/databases”.

      Hope this may help you , Feel free to ask 🙂

      Thanks

  • Subham Jana

    import com.androidtutorialshub.loginregister.R;

    What is ‘R’ here…?
    Not getting any link

    • Admin

      Hi Subham,

      Android R.java is an auto-generated file by aapt (Android Asset Packaging Tool) that contains resource IDs for all the resources of res/ directory. If you create any component in the activity_main.xml file, id for the corresponding component is automatically created in this file.

      Are you using code cloned from github?
      If yes then clean the code and rebuilt it error will be resolved.
      If not then remove this import statement.

      Hope this may help you , Feel free to ask 🙂

      Thanks

  • Shagun Choudhary

    where is the database UserManager.db stored in project ?

    • Lalit Vasan

      Hi Shagun,

      Database files are stored in path “/data/data/[your_package_name]/databases”.

      Hope this may help you , Feel free to ask 🙂

      Thanks

      • Shagun Choudhary

        I was asking that how could I access this database file in my android project in android studio as i want to make some changes in it

        • Lalit Vasan

          Hi Shagun,

          Following are the steps to access the file:-

          1. Download and install SQLiteBrowser(http://sqlitebrowser.org/).
          2. Open DDMS via Tools > Android > Android Device Monitor
          3. Click on your device on the left.
          4. Go to File Explorer (one of the tabs on the right), go to /data/data/databases
          5. Select the database by just clicking on it.
          6. Go to the top right corner of the Android Device Monitor window. Click on the ‘pull a file from the device’ button.
          7. A window will open asking you where you want to save your database file. Save it anywhere you want on your PC.
          8. Now, open the SQLiteBrowser you installed. Click on ‘open database’, navigate to the location you saved the database file, and open. You can now view the contents of your database.

          Hope this may help you , Feel free to ask 🙂

          Thanks

          • Shagun Choudhary

            Thanks, but when I clk on data it doesn’t opens anything

  • Marcos Vinicius Ducatti

    Hello! Thank you for the tutorial!

    Im doing a school project and I need to add a picture to the profile to the user and displaying it on a new profile xml that Ill create, would you mind guiding me on how can I add the picture?

    Thank you again!

    • Lalit Vasan

      Hi Marcos,

      There are some changes you have to do to store and display pic.

      1) Modify the structure of the user table add one new field to store photo path.
      2) On Registration screen add UI for profile pic.
      3) On click on profile pic UI write a code to get it from camera or from gallery. After you get pic from any media retain the image path in variable.
      4) After filling all details on registration page with photo path store that in database.
      5) Now you have record of user with image path. so now you can show user info with user pic on profile screen.

      Hope this may help you , Feel free to ask 🙂

      Thanks

  • Hassan Ali Mughal

    Hello sir in the given code i am trying and i succeed but sir i have a little bit problem ,the ListActivity is not shown no error is occured but my email id and passord are not shown the interface login me again and again but the list activity is not shown!!

  • Pranit Darekar

    how can I view my database structure(all the tables and the data in it) like we do in localhost where we can see the complete database?

    • Lalit Vasan

      Hi Pranit,

      Database files are stored in storage at path “/data/data/[your_package_name]/databases”. Database file extension is .db. Copy and paste that file to your machine and download Sqlite Browser (http://sqlitebrowser.org/) to view database structure.

      Hope this may help you , Feel free to ask 🙂

      Thanks

  • Hassan Ali Mughal

    Hi admin my question is
    public void updateUser(User user) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(COLUMN_USER_NAME, user.getName());
    values.put(COLUMN_USER_EMAIL, user.getEmail());
    values.put(COLUMN_USER_PASSWORD, user.getPassword());
    values.put(COLUMN_USER_AGE, user.getAge());

    // updating row
    db.update(TABLE_USER, values, COLUMN_USER_ID + ” = ?”,
    new String[]{String.valueOf(user.getId())});
    db.close();
    }
    in this following codes the updateUser is never used kindly help to solved this problem!!

  • Hassan Ali Mughal

    And one more thing if i add extra data e.g age, gender, height, and weight then the programm given no error but in excuting the programm the registration is done but in login system given the error and the error is Cursor error on this side
    Cursor cursor = db.query(TABLE_USER, //Table to query
    columns, //columns to return
    null, //columns for the WHERE clause
    null, //The values for the WHERE clause
    null, //group the rows
    null,
    null,//filter by row groups
    sortOrder); //The sort order

    • Lalit Vasan

      Hi Hassan,

      Have you checked the SQL query to create table. It should be like this

      // User Table Columns names
      private static final String COLUMN_USER_ID = “user_id”;
      private static final String COLUMN_USER_NAME = “user_name”;
      private static final String COLUMN_USER_EMAIL = “user_email”;
      private static final String COLUMN_USER_PASSWORD = “user_password”;
      private static final String COLUMN_USER_AGE = “user_age”;
      private static final String COLUMN_USER_GENDER = “user_gender”;
      private static final String COLUMN_USER_HEIGHT = “user_height”;
      private static final String COLUMN_USER_WEIGHT = “user_password”;

      // create table sql query
      private String CREATE_USER_TABLE = “CREATE TABLE ” + TABLE_USER + “(”
      + COLUMN_USER_ID + ” INTEGER PRIMARY KEY AUTOINCREMENT,” + COLUMN_USER_NAME + ” TEXT,” + COLUMN_USER_EMAIL + ” TEXT,” + COLUMN_USER_PASSWORD + ” TEXT,” + COLUMN_USER_AGE + ” TEXT,” + COLUMN_USER_GENDER + ” TEXT,” + COLUMN_USER_HEIGHT + ” TEXT,” + COLUMN_USER_WEIGHT + ” TEXT” + “)”;

      and also add the column in columns array like
      String[] columns = {
      COLUMN_USER_ID,
      COLUMN_USER_EMAIL,
      COLUMN_USER_NAME,
      COLUMN_USER_PASSWORD,
      COLUMN_USER_AGE,
      COLUMN_USER_GENDER,
      COLUMN_USER_HEIGHT,
      COLUMN_USER_WEIGHT
      };

      Hope this may help you , Feel free to ask 🙂

      Thanks

      • Hassan Ali Mughal

        Hi admin
        In this given scenario i try this same thing but i facing the same error , if i not add the extra data then its not given the error or display the correct output but i add the extra data then its occur the logical error, the error is wrong email ur password

        • Lalit Vasan

          Extra data ?

          • Lalit Vasan

            Hi Hassan,

            There is error in your create table statement you have missed to put “,” after every datatype(TEXT) .

            WRONG SQL
            // create table sql query
            private String CREATE_USER_TABLE = “CREATE TABLE ” + TABLE_USER + “(”
            + COLUMN_USER_ID + ” INTEGER PRIMARY KEY AUTOINCREMENT,” + COLUMN_USER_NAME + ” TEXT,”
            + COLUMN_USER_EMAIL + ” TEXT,” + COLUMN_USER_PASSWORD + ” TEXT” + COLUMN_USER_AGE + ” INTEGER” +COLUMN_USER_GENDER + ” TEXT”
            +COLUMN_USER_HEIGHT + ” TEXT” +COLUMN_USER_WEIGHT + ” TEXT”+ “)”;

            RIGHT SQL
            // create table sql query
            private String CREATE_USER_TABLE = “CREATE TABLE ” + TABLE_USER + “(”
            + COLUMN_USER_ID + ” INTEGER PRIMARY KEY AUTOINCREMENT,” + COLUMN_USER_NAME + ” TEXT,”
            + COLUMN_USER_EMAIL + ” TEXT,” + COLUMN_USER_PASSWORD + ” TEXT,” + COLUMN_USER_AGE + ” INTEGER” +COLUMN_USER_GENDER + ” TEXT,”
            +COLUMN_USER_HEIGHT + ” TEXT,” +COLUMN_USER_WEIGHT + ” TEXT”+ “)”;

            Hope this may help you , Feel free to ask 🙂

            Thanks

  • Hassan Ali Mughal

    Hi adim i added new data successfuly but at this time the logical error is the resgiatration is successfully but in the login page i put correct email ur pascode but it can’t log me error is wrong email ur passwrd!!

  • kapil Gupta

    sir there is one request if possible please upload a tutorials for (MySQL or Firebase)
    for store , fetch ,update and delete the information .

    • Lalit Vasan

      Hi Kapil,

      Thanks for the suggestion, soon I will write the tutorial.

  • aparna lavanuru

    while running the app i created a account and while login , my login page is suddenly closing please help me

    • Lalit Vasan

      Hi Aparna,

      Kindly post the code and logs so that i investigate the actual error

  • Benudhar

    Hello sir,
    I want display only current user profile in user ListActivity. I have been trying but it is not working please help me.

    Thanks
    Benudhar

    • Lalit Vasan

      Hi Benudhar,

      What is the actual error? Are you using the downloaded code via given link?

  • Hassan Ali Mughal

    Hi Admin
    It is my DB class in class if i add email, name and passcode then it makes the correct out put but if i add extra data in given below code, it registerd user successfully but i put correct email and passcode on login page then its says the user email and passcode is wrong kindly chck by DB and find where the mistake!
    public class DatabaseHelper extends SQLiteOpenHelper {
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = “UserManager.db”;

    // User table name
    private static final String TABLE_USER = “user”;

    // User Table Columns names
    private static final String COLUMN_USER_ID = “user_id”;
    private static final String COLUMN_USER_NAME = “user_name”;
    private static final String COLUMN_USER_EMAIL = “user_email”;
    private static final String COLUMN_USER_PASSWORD = “user_password”;
    private static final String COLUMN_USER_AGE = “user_age”;
    private static final String COLUMN_USER_GENDER = “user_gender”;
    private static final String COLUMN_USER_HEIGHT = “user_height”;
    private static final String COLUMN_USER_WEIGHT = “user_weight”;

    // create table sql query
    private String CREATE_USER_TABLE = “CREATE TABLE ” + TABLE_USER + “(”
    + COLUMN_USER_ID + ” INTEGER PRIMARY KEY AUTOINCREMENT,” + COLUMN_USER_NAME + ” TEXT,”
    + COLUMN_USER_EMAIL + ” TEXT,” + COLUMN_USER_PASSWORD + ” TEXT” + COLUMN_USER_AGE + ” INTEGER” +COLUMN_USER_GENDER + ” TEXT”
    +COLUMN_USER_HEIGHT + ” TEXT” +COLUMN_USER_WEIGHT + ” TEXT”+ “)”;

    // drop table sql query
    private String DROP_USER_TABLE = “DROP TABLE IF EXISTS ” + TABLE_USER;

    /**
    * Constructor
    *
    * @param context
    */
    public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
    db.execSQL(CREATE_USER_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    //Drop User Table if exist
    db.execSQL(DROP_USER_TABLE);

    // Create tables again
    onCreate(db);

    }

    /**
    * This method is to create user record
    *
    * @param user
    */
    public void addUser(User user) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(COLUMN_USER_NAME, user.getName());
    values.put(COLUMN_USER_EMAIL, user.getEmail());
    values.put(COLUMN_USER_PASSWORD, user.getPassword());
    values.put(COLUMN_USER_AGE, user.getAge());
    values.put(COLUMN_USER_GENDER, user.getGender());
    values.put(COLUMN_USER_HEIGHT, user.getHeight());
    values.put(COLUMN_USER_WEIGHT, user.getWeight());

    // Inserting Row
    db.insert(TABLE_USER, null, values);
    db.close();
    }

    /**
    * This method is to fetch all user and return the list of user records
    *
    * @return list
    */
    public List getAllUser() {
    // array of columns to fetch
    String[] columns = {
    COLUMN_USER_ID,
    COLUMN_USER_EMAIL,
    COLUMN_USER_NAME,
    COLUMN_USER_PASSWORD,
    COLUMN_USER_AGE,
    COLUMN_USER_GENDER,
    COLUMN_USER_HEIGHT,
    COLUMN_USER_WEIGHT
    };
    // sorting orders
    String sortOrder =
    COLUMN_USER_NAME + ” ASC”;
    List userList = new ArrayList();

    SQLiteDatabase db = this.getReadableDatabase();

    // query the user table
    /**
    * Here query function is used to fetch records from user table this function works like we use sql query.
    * SQL query equivalent to this query function is
    * SELECT user_id,user_name,user_email,user_password FROM user ORDER BY user_name;
    */
    Cursor cursor = db.query(TABLE_USER, //Table to query
    columns, //columns to return
    null, //columns for the WHERE clause
    null, //The values for the WHERE clause
    null, //group the rows
    null,
    null,
    //filter by row groups
    sortOrder); //The sort order

    // Traversing through all rows and adding to list
    if (cursor.moveToFirst()) {
    do {
    User user = new User();
    user.setId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(COLUMN_USER_ID))));
    user.setName(cursor.getString(cursor.getColumnIndex(COLUMN_USER_NAME)));
    user.setEmail(cursor.getString(cursor.getColumnIndex(COLUMN_USER_EMAIL)));
    user.setPassword(cursor.getString(cursor.getColumnIndex(COLUMN_USER_PASSWORD)));
    user.setAge(cursor.getString(cursor.getColumnIndex(COLUMN_USER_AGE)));
    user.setGender(cursor.getString(cursor.getColumnIndex(COLUMN_USER_GENDER)));
    user.setHeight(cursor.getString(cursor.getColumnIndex(COLUMN_USER_HEIGHT)));
    user.setWeight(cursor.getString(cursor.getColumnIndex(COLUMN_USER_WEIGHT)));
    // Adding user record to list
    userList.add(user);
    } while (cursor.moveToNext());
    }
    cursor.close();
    db.close();

    // return user list
    return userList;
    }

    public boolean checkUser(String email) {

    // array of columns to fetch
    String[] columns = {
    COLUMN_USER_ID
    };
    SQLiteDatabase db = this.getReadableDatabase();

    // selection criteria
    String selection = COLUMN_USER_EMAIL + ” = ?”;

    // selection argument
    String[] selectionArgs = {email};

    // query user table with condition
    /**
    * Here query function is used to fetch records from user table this function works like we use sql query.
    * SQL query equivalent to this query function is
    * SELECT user_id FROM user WHERE user_email = ‘jack@androidtutorialshub.com’;
    */
    Cursor cursor = db.query(TABLE_USER, //Table to query
    columns, //columns to return
    selection, //columns for the WHERE clause
    selectionArgs, //The values for the WHERE clause
    null, //group the rows
    null, //filter by row groups
    null,
    null);
    //The sort order
    int cursorCount = cursor.getCount();
    cursor.close();
    db.close();

    if (cursorCount > 0) {
    return true;
    }

    return false;
    }

    /**
    * This method to check user exist or not
    *
    * @param email
    * @param password
    * @return true/false
    */
    public boolean checkUser(String email, String password) {

    // array of columns to fetch
    String[] columns = {
    COLUMN_USER_ID
    };
    SQLiteDatabase db = this.getReadableDatabase();
    // selection criteria
    String selection = COLUMN_USER_EMAIL + ” = ?” + ” AND ” + COLUMN_USER_PASSWORD + ” = ?”;

    // selection arguments
    String[] selectionArgs = {email, password};

    // query user table with conditions
    /**
    * Here query function is used to fetch records from user table this function works like we use sql query.
    * SQL query equivalent to this query function is
    * SELECT user_id FROM user WHERE user_email = ‘jack@androidtutorialshub.com’ AND user_password = ‘qwerty’;
    */
    Cursor cursor = db.query(TABLE_USER, //Table to query
    columns, //columns to return
    selection, //columns for the WHERE clause
    selectionArgs, //The values for the WHERE clause
    null, //group the rows
    null, //filter by row groups
    null); //The sort order

    int cursorCount = cursor.getCount();

    cursor.close();
    db.close();
    if (cursorCount > 0) {
    return true;
    }

    return false;
    }

  • Jyoti

    can smone please help me to build same login and register for two user roles?I have to create two types of user one is user and other doctor

    • Lalit Vasan

      Hi Jyoti,

      As per you requirement you have to make changes as follows:-

      1) Add one more column in user table for user type. Which store o for normal user and 1 for doctor.
      2) Take input from user registration screen for user type, use radio buttons for normal user and doctor and store the 0 if user selected and 1 if doctor selected to user type column in user table.
      3) while login check the user credentials are valid. And also fetch the user details from which you can check the user type, whether user is normal user or doctor.

      Hope this may help you , Feel free to ask 🙂

      Thanks

  • Trust Kayz

    hie I am new in android development and thanks for the article but I am having a problem adding the dependencies. When trying to rebuild the project I get the error

    Error:(11, 1) A problem occurred evaluating root project ‘loginregister’.
    > Could not find method compile() for arguments [com.android.support:appcompat-v7:23.4.0] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.

  • Hippie Stereo

    Hello.
    Great tutorial, everything works great.
    Thanks a lot 🙂

    • Lalit Vasan

      Welcome Hippie Stereo.

  • Arun Sharma

  • Usman Khan

    Hi Lalit, I am trying to implement the UserListActivity to a fragment rather than an activity. This is because I am using tabbed screens. I have been trying to implement it but am having some trouble. Could you please point me in the right direction. Thanks

    • Lalit Vasan

      Hi Usman,

      Sure I will guide you. Kindly elaborate the issue you are facing.

      • Usman Khan

        Thanks for getting back to me. I followed your tutorial and I managed to get the login and register working perfectly. The application I am making takes contacts and adds it to the database, which is already setup in the DatabaseHelper. I want to display the contacts on the MainActivity which is a navigation drawer activity with tabs. This means I need to work with fragments rather then make a new activity to display the contacts. Since I am new to Android development I didn’t know how to convert the UserListActivity properly to a fragment. This is what I have already:

        public class EContactsFragment extends Fragment {

        private RecyclerView recyclerViewContacts;
        private List listContacts;
        private ContactRecyclerAdapter contactRecyclerAdapter;
        private DatabaseHelper databaseHelper;
        @Override
        public View onCreateView(@Nullable LayoutInflater inflater, ViewGroup container,@Nullable Bundle savedInstanceState) {

        return inflater.inflate(R.layout.econtacts_fragment, container, false);
        }

        private void initObjects (){
        listContacts = new ArrayList();
        contactRecyclerAdapter = new ContactRecyclerAdapter(listContacts);

        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
        recyclerViewContacts.setLayoutManager(mLayoutManager);
        recyclerViewContacts.setItemAnimator(new DefaultItemAnimator());
        recyclerViewContacts.setHasFixedSize(true);
        recyclerViewContacts.setAdapter(contactRecyclerAdapter);
        databaseHelper = new DatabaseHelper(this.getContext());

        // getDataFromSQLite();
        }

        private void initViews(){
        recyclerViewContacts = (RecyclerView) getView().findViewById(R.id.recyclerViewContacts);
        }

        private void getDataFromSQLite() {
        // AsyncTask is used that SQLite operation not blocks the UI Thread.
        new AsyncTask() {
        @Override
        protected Void doInBackground(Void… params) {
        listContacts.clear();
        listContacts.addAll(databaseHelper.getAllContact());

        return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        contactRecyclerAdapter.notifyDataSetChanged();
        }
        }.execute();
        }
        }

        The code seems to always crash my application when running getDataFromSQLite. I am not sure if this is the issue but there is a warning over this function that says “This ASyncTask class should be static or leaks might occur” Is this normal?

        I would really appreciate your help on this as I have been trying for a long time. Please let me know if you need to see anymore code. Thanks

        • Lalit Vasan

          Call both method in onCreateView().

          • Usman Khan

            Hi Lalit, I tried doing that but it still crashes the application. initViews() works fine, the issue is when initObjects() is called. I think it may be an issue with the database. Do you know of anything else I could do? I would be forever grateful if you could help me with this. Thanks

          • Lalit Vasan

            Hi Usman
            Are u calling initview first and then initobject? Also post the logs of the error.

          • Usman Khan

            Hi Lalit,
            Yes I call initViews() first. The log of the error is posted below:
            java.lang.NullPointerException: Attempt to invoke virtual method ‘android.view.View android.view.View.findViewById(int)’ on a null object reference
            at ecard.ecardprototype.Fragments.EContactsFragment.initViews(EContactsFragment.java:56)
            at ecard.ecardprototype.Fragments.EContactsFragment.onCreateView(EContactsFragment.java:35)

          • Lalit Vasan

            This is a null pointer exception due to some object references. Either you have not declared the objects correctly or not defined the ids correctly. Clean your project once.

            If problem is not solved then I see it via TeamViewer

          • Usman Khan

            I tried cleaning the project. Not sure how to fix the issue, is it possible to setup teamviewer? Many thanks

          • Lalit Vasan

            Add me on skype :- vasanlalit

          • Usman Khan

            Request sent. Thanks

Show Buttons
Hide Buttons