Android Login and Register with SQLite Database Tutorial


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

What is SQLite?

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

Key point to understand regarding SQLite :-

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

Let’s Get it Working

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

DownloadCode
 
github

Step 1) Update build.gradle file.

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

Step 2) Update strings.xml.

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

Step 3) Update colors.xml.

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

Step 4) Update styles.xml.

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

Step 5) Add Logo Image.

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

Android Tutorials Hub Logo

Android Tutorials Hub Logo

Step 6) Create User model class.

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

Step 7) Create DatabaseHelper class.

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

Methods and functionality

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

User Table Schema

User Table Schema

Step 8) Create activity_login.xml.

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

activity_login.xml would result a screen like this:

Login Screen

Login Screen

Step 8) Create InputValidation class.

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





Step 9) Create LoginActivity class.

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

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

Login Screen with Input Validation

Login Screen with Input Validation

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

Login Screen With SQLite Validation

Login Screen With SQLite Validation

Step 10) Create activity_register.xml.

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

activity_register.xml would result a screen like this:

Registration Screen

Registration Screen

Step 11) Create RegisterActivity class.

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

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

Register Screen with Input Validation

Register Screen with Input Validation

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

Register Screen with input fields filled

Register Screen with filled input fields

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

Register Screen with Registration Success Message

Register Screen with Registration Success Message

Step 12) Create activity_users_list.xml.

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

activity_users_list.xml would result a screen like this:

User List Screen

User List Screen

Step 13) Writing the Adapter Class.

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

item_user_recycler.xml

Step 14) Create UsersListActivity class.

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

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

User List Screen After Login

User List Screen After Login

Step 15) Update AndroidManifest.xml.

DownloadCode
 
github


Enjoy Coding and Share Knowledge

  • Streatico HD

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

    thanks Please reply back

    • Admin

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

      Hope this may help you 🙂

  • Sandeep

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

    • Admin

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

  • Pooja Ravi

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

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

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

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

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

    • Admin

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

      Hope this may help you 🙂

    • 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

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

  • 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

  • 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

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

  • 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

Show Buttons
Hide Buttons