Blog purpose for android basic example for android app developer. any query please my contact

Saturday, 23 May 2020

how to create login page in android studio using sqlite database

how to create login page in android studio using sqlite database

In this Article today learn how to create  login page in android studio using sqlite databaseWhether it’s a site, use, or code login and certification are really important components for most of them. In the post we will see how we can accomplish login and certification using SQLite information. In the program we would be able to log in and enter the new user. This program has two screens opening one is a login screen where we will only login with our credentials. The second display is a register display where we will send new users. Then let’s go started

Most applications nowadays have the authority structure in forms of Facebook login, Google login, simple old e-mail login, and more. As a matter of fact, Sketchware uses Google Login in this program, too. Having the authority structure is a good way to keep users organized. Today, we'll see how to create the standard username/password login structure on Sketchware.

 

Follow the code full source code how to create login page in android studio using SQLite database:


1.MainActivity.java:

package com.akash.loginsqlite;

import android.content.Intent;

import android.os.Bundle;

import android.text.Html;

import android.text.Spanned;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.TextView;


import androidx.appcompat.app.AppCompatActivity;


import com.google.android.material.snackbar.Snackbar;

import com.google.android.material.textfield.TextInputLayout;


public class MainActivity extends AppCompatActivity {


    //Declaration EditTexts

    EditText editTextEmail;

    EditText editTextPassword;


    //Declaration TextInputLayout

    TextInputLayout textInputLayoutEmail;

    TextInputLayout textInputLayoutPassword;


    //Declaration Button

    Button buttonLogin;


    //Declaration SqliteHelper

    SqliteHelper sqliteHelper;


    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        sqliteHelper = new SqliteHelper(this);

       // initCreateAccountTextView();

        initViews();


        //set click event of login button

        buttonLogin.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View view) {


                if (validate()) {


                    //Get values from EditText fields

                    String Email = editTextEmail.getText().toString();

                    String Password = editTextPassword.getText().toString();


                    User currentUser = sqliteHelper.Authenticate(new User(null, null, Email, Password));


                    if (currentUser != null) {

                        Snackbar.make(buttonLogin, "Successfully Logged in!", Snackbar.LENGTH_LONG).show();


                        //User Logged in Successfully Launch You home screen activity

                       /* Intent intent=new Intent(LoginActivity.this,HomeScreenActivity.class);

                        startActivity(intent);

                        finish();*/

                    } else {


                        //User Logged in Failed

                        Snackbar.make(buttonLogin, "Failed to log in , please try again", Snackbar.LENGTH_LONG).show();


                    }

                }

            }

        });



    }


    //this method used to set Create account TextView text and click event( maltipal colors

    // for TextView yet not supported in Xml so i have done it programmatically)

    /*private void initCreateAccountTextView() {

        TextView textViewCreateAccount = (TextView) findViewById(R.id.textViewCreateAccount);

        textViewCreateAccount.setText(fromHtml("<font color='#ffffff'>I don't have account yet. </font><font color='#0c0099'>create one</font>"));

        textViewCreateAccount.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View view) {

                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);

               startActivity(intent);

            }

        });

    }*/


    //this method is used to connect XML views to its Objects

    private void initViews() {

        editTextEmail = (EditText) findViewById(R.id.editEmail);

        editTextPassword = (EditText) findViewById(R.id.editPassword);

     //   textInputLayoutEmail = (TextInputLayout) findViewById(R.id.textInputLayoutEmail);

     //   textInputLayoutPassword = (TextInputLayout) findViewById(R.id.textInputLayoutPassword);

        buttonLogin = (Button) findViewById(R.id.buttonLogin);


    }


    //This method is for handling fromHtml method deprecation

    @SuppressWarnings("deprecation")

    public static Spanned fromHtml(String html) {

        Spanned result;

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {

            result = Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY);

        } else {

            result = Html.fromHtml(html);

        }

        return result;

    }


    //This method is used to validate input given by user

    public boolean validate() {

        boolean valid = false;


        //Get values from EditText fields

        String Email = editTextEmail.getText().toString();

        String Password = editTextPassword.getText().toString();


        //Handling validation for Email field

        if (!android.util.Patterns.EMAIL_ADDRESS.matcher(Email).matches()) {

            valid = false;

            textInputLayoutEmail.setError("Please enter valid email!");

        } else {

            valid = true;

            textInputLayoutEmail.setError(null);

        }


        //Handling validation for Password field

        if (Password.isEmpty()) {

            valid = false;

            textInputLayoutPassword.setError("Please enter valid password!");

        } else {

            if (Password.length() > 5) {

                valid = true;

                textInputLayoutPassword.setError(null);

            } else {

                valid = false;

                textInputLayoutPassword.setError("Password is to short!");

            }

        }


        return valid;

    }



}



2.create a class SqliteHelper.java:

package com.akash.loginsqlite;

import android.content.ContentValues;

import android.content.Context;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteOpenHelper;


/**

 * Created by amardeep on 10/26/2017.

 */


public class SqliteHelper extends SQLiteOpenHelper {


    //DATABASE NAME

    public static final String DATABASE_NAME = "loopwiki.com";


    //DATABASE VERSION

    public static final int DATABASE_VERSION = 1;


    //TABLE NAME

    public static final String TABLE_USERS = "users";


    //TABLE USERS COLUMNS

    //ID COLUMN @primaryKey

    public static final String KEY_ID = "id";


    //COLUMN user name

    public static final String KEY_USER_NAME = "username";


    //COLUMN email

    public static final String KEY_EMAIL = "email";


    //COLUMN password

    public static final String KEY_PASSWORD = "password";


    //SQL for creating users table

    public static final String SQL_TABLE_USERS = " CREATE TABLE " + TABLE_USERS

            + " ( "

            + KEY_ID + " INTEGER PRIMARY KEY, "

            + KEY_USER_NAME + " TEXT, "

            + KEY_EMAIL + " TEXT, "

            + KEY_PASSWORD + " TEXT"

            + " ) ";



    public SqliteHelper(Context context) {

        super(context, DATABASE_NAME, null, DATABASE_VERSION);

    }


    @Override

    public void onCreate(SQLiteDatabase sqLiteDatabase) {

        //Create Table when oncreate gets called

        sqLiteDatabase.execSQL(SQL_TABLE_USERS);


    }


    @Override

    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

        //drop table to create new one if database version updated

        sqLiteDatabase.execSQL(" DROP TABLE IF EXISTS " + TABLE_USERS);

    }


    //using this method we can add users to user table

    public void addUser(User user) {


        //get writable database

        SQLiteDatabase db = this.getWritableDatabase();


        //create content values to insert

        ContentValues values = new ContentValues();


        //Put username in  @values

        values.put(KEY_USER_NAME, user.userName);


        //Put email in  @values

        values.put(KEY_EMAIL, user.email);


        //Put password in  @values

        values.put(KEY_PASSWORD, user.password);


        // insert row

        long todo_id = db.insert(TABLE_USERS, null, values);

    }


    public User Authenticate(User user) {

        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_USERS,// Selecting Table

                new String[]{KEY_ID, KEY_USER_NAME, KEY_EMAIL, KEY_PASSWORD},//Selecting columns want to query

                KEY_EMAIL + "=?",

                new String[]{user.email},//Where clause

                null, null, null);


        if (cursor != null && cursor.moveToFirst()&& cursor.getCount()>0) {

            //if cursor has value then in user database there is user associated with this given email

            User user1 = new User(cursor.getString(0), cursor.getString(1), cursor.getString(2), cursor.getString(3));


            //Match both passwords check they are same or not

            if (user.password.equalsIgnoreCase(user1.password)) {

                return user1;

            }

        }


        //if user password does not matches or there is no record with that email then return @false

        return null;

    }


    public boolean isEmailExists(String email) {

        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_USERS,// Selecting Table

                new String[]{KEY_ID, KEY_USER_NAME, KEY_EMAIL, KEY_PASSWORD},//Selecting columns want to query

                KEY_EMAIL + "=?",

                new String[]{email},//Where clause

                null, null, null);


        if (cursor != null && cursor.moveToFirst()&& cursor.getCount()>0) {

            //if cursor has value then in user database there is user associated with this given email so return true

            return true;

        }


        //if email does not exist return false

        return false;

    }

}


3.create a class User.java:

package com.akash.loginsqlite;


public class User {

    public String id;

    public String userName;

    public String email;

    public String password;


    public User(String id, String userName, String email, String password) {

        this.id = id;

        this.userName = userName;

        this.email = email;

        this.password = password;

    }


}


4.activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:id="@+id/activity_main"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:paddingBottom="@dimen/activity_vertical_margin"

    android:paddingLeft="@dimen/activity_horizontal_margin"

    android:paddingRight="@dimen/activity_horizontal_margin"

    android:paddingTop="@dimen/activity_vertical_margin"

    tools:context=".MainActivity">


    <TextView

        android:text="SQLite User Login Screen"

        android:gravity="center"

        android:textSize="20dp"

        android:textColor="#000"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_alignParentTop="true"

        android:layout_centerHorizontal="true"

        android:id="@+id/textView" />


    <EditText

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:inputType="textEmailAddress"

        android:hint="Enter Email"

        android:textColor="#000"

        android:ems="10"

        android:layout_below="@+id/textView"

        android:layout_centerHorizontal="true"

        android:layout_marginTop="20dp"

        android:id="@+id/editEmail"

        android:gravity="center"/>


    <EditText

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:inputType="textPassword"

        android:hint="Enter Password"

        android:textColor="#000"

        android:ems="10"

        android:layout_below="@+id/editEmail"

        android:layout_centerHorizontal="true"

        android:layout_marginTop="20dp"

        android:id="@+id/editPassword"

        android:gravity="center"/>


    <Button

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:id="@+id/buttonLogin"

        android:layout_below="@+id/editPassword"

        android:layout_marginTop="20dp"

        android:text="Log IN "/>


    <Button

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:id="@+id/buttonRegister"

        android:layout_below="@+id/buttonLogin"

        android:layout_marginTop="20dp"

        android:text="Not Log IN | Register From here "/>


</RelativeLayout>


5.AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.akash.loginsqlite">


    <application

        android:allowBackup="true"

        android:icon="@mipmap/ic_launcher"

        android:label="@string/app_name"

        android:roundIcon="@mipmap/ic_launcher_round"

        android:supportsRtl="true"

        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />


                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

    </application>


</manifest>



 


No comments:

Post a Comment