“This is my 26th day of participating in the First Challenge 2022. For details: First Challenge 2022

SQLite is a lightweight database that comes with the AndroidSDK. This article demonstrates the use of SQLite to implement the login registration module.

Login screen


      
<layout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ImageView
            android:id="@+id/headoortrait"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            android:src="@drawable/ic_login_picture" />

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/et_username_layout"
            style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="26dp"
            android:layout_marginStart="16dp"
            android:layout_marginEnd="16dp"
            app:layout_constraintTop_toBottomOf="@+id/headoortrait"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent">

            <com.google.android.material.textfield.TextInputEditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="User Account"/>
        </com.google.android.material.textfield.TextInputLayout>

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/et_password_layout"
            style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginEnd="16dp"
            app:layout_constraintTop_toBottomOf="@+id/et_username_layout"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent">
            <com.google.android.material.textfield.TextInputEditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textPassword"
                android:hint="Password"/>
        </com.google.android.material.textfield.TextInputLayout>

      

        <Button
            android:id="@+id/btn_login"
            android:layout_width="match_parent"
            android:layout_height="56dp"
            android:text="Login"
            android:layout_marginStart="16dp"
            android:layout_marginEnd="16dp"
            app:layout_constraintTop_toBottomOf="@+id/et_username_layout" />

        <Button
            android:id="@+id/btn_register"
            android:layout_width="match_parent"
            android:layout_height="56dp"
            android:text="Registered"
            android:layout_marginStart="16dp"
            android:layout_marginEnd="16dp"
            app:layout_constraintTop_toBottomOf="@+id/btn_login" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>
Copy the code

The registration screen


      
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clickable="true"
    android:background="@color/white">
<! -- <ImageView-->
<! -- android:layout_width="match_parent"-->
<! -- android:layout_height="match_parent"-->
<! -- android:scaleType="fitCenter"-->
<! -- app:srcCompat="@drawable/bg_register" />-->

    <com.google.android.material.textfield.TextInputLayout
        style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
        android:id="@+id/user_name_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="90dp"
        android:layout_marginStart="16dp"
        android:layout_marginEnd="16dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:layout_editor_absoluteY="160dp">

        <com.google.android.material.textfield.TextInputEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Username" />
    </com.google.android.material.textfield.TextInputLayout>

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/phone_number_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
        android:layout_marginTop="26dp"
        android:layout_marginStart="16dp"
        android:layout_marginEnd="16dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/user_name_layout"
        tools:layout_editor_absoluteY="160dp">

        <com.google.android.material.textfield.TextInputEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Mobile phone Number" />
    </com.google.android.material.textfield.TextInputLayout>
    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/password_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginEnd="16dp"
        style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
        android:layout_marginTop="26dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/phone_number_layout"
        tools:layout_editor_absoluteY="160dp">

        <com.google.android.material.textfield.TextInputEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPassword"
            android:hint="Password" />
    </com.google.android.material.textfield.TextInputLayout>

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/confirm_password_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
        android:layout_marginTop="26dp"
        android:layout_marginStart="16dp"
        android:layout_marginEnd="16dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/password_layout"
        tools:layout_editor_absoluteY="160dp">

        <com.google.android.material.textfield.TextInputEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPassword"
            android:hint="Confirm password" />
    </com.google.android.material.textfield.TextInputLayout>

    <Button
        android:id="@+id/btn_register"
        android:layout_width="130dp"
        android:layout_height="56dp"
        android:text="-"
        android:layout_marginTop="26dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/confirm_password_layout" />
</androidx.constraintlayout.widget.ConstraintLayout>
Copy the code

  style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
Copy the code

Login data entity class

/ * * *@Description
 * @AuthorNine Wolf *@Time2022/2/20 returned from * /
public class UserBean {

    private int id;
    /** * User name */
    private String name;

    /** * Password */
    private String password;

    /** * Mobile phone number */
    private String phoneNumber;

    /** * age */
    private String age;
    /** * age */
    private String sex;

    /** * Authentication result */
    private String authenticationResults;

    /** ** avatar */
    private String avatar;

    /** * id */
    private String idNumber;
}
Copy the code

SQLite

I’m not going to write set and get

The DAO model

The interface encapsulates the DAO model. With this encapsulation, you can add, delete, change, and query the database only by calling methods.

baseDao

public interface BaseDao<T> {
 void add(T entity);
 void delete(int id);
 void update(T entity);
 List<T> query(a);
}
Copy the code

SQLiteOpenHelper

SQLite helper ————SQLiteOpenHelper SQLiteOpenHelper is a helper class for SQLiteDatabase that manages database creation and version updates. It is common to create a class that inherits it and then implement its onCreate and onUpgrade methods

Constructor to pass a created database name and version parameters

/ * * *@Description
 * @Author
 * @Time2022/2/19 18:01 * /
public class SQLiteDatabaseHelper extends SQLiteOpenHelper {

    private static final String DB_NAME="travelsafty.db";// Database name
    / / version number
    private static final int TRAVELSAFTY_VERSION =1;
    /** * the UserBean field must correspond to the UserBean field
    public static final String TABLE_USER="user";
    public static final String USER_ID="id";
    public static final String USER_NAME="name";
    public static final String USER_PASS_WORD = "password";
    public static final String USER_PHONE_NUMBER = "phoneNumber";
    public static final String USER_AGE = "age";
    public static final String USER_SEX = "sex";
    public static final String USER_AUTHENTICATION_RESULTS = "authenticationResults";
    public static final String USER_AVATAR = "avatar";
    public static final String USER_ID_NUMBER = "idNumber";

/ / create a table
    public static final String CREATE_USER ="create table user ( id integer primary key autoincrement, name text, password text, phoneNumber text, age text, sex text, authenticationResults text, avatar text,idNumber text)";

    public SQLiteDatabaseHelper(Context context) {
        super(context,DB_NAME,null, TRAVELSAFTY_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
       // Perform the create UserBean table
        db.execSQL(CREATE_USER);

    }

    /** update database * 1, the first time the database is created, this method will not run * 2, clean the database again (equivalent to the first time), this method will not run */, the database already exists, and the version is higher, this method will call */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Use the for iteration upgrade, so that different versions of the database for different users can be compatible with the latest update
        for (int j = oldVersion + 1; j <= newVersion; j++) { upgradeTo(db, j); }}private void upgradeTo(SQLiteDatabase db, int version) {
        try {
            switch (version) {
                case 1:

                    break;
                case 2:
                  
                    break;
                case 3:

                    break;
                case 4:
                    break;
                default:
                    break; }}catch(Exception e) { e.printStackTrace(); }}}Copy the code

The data type of SQLite

Five common data types for SQLite

  • NULL: indicates a NULL value
  • INTEGER: Stores an INTEGER, which can be 1,2,3,4,6, or 8 bits, depending on the size.
  • REAL: IEEE floating point number
  • TEXT: Stores as a string
  • BLOB: Stores as binary values without any changes.

SQLiteDatabase

Use SQLiteDatabase to complete the data processing

  • Add (Create)
  • Query (Retrieve)
  • Update (Update)
  • Delete (Delete)

Referred to as CRUD


/ * * *@Description
 * @AuthorNine Wolf *@Time 2022/2/20 18:15
 */
public class UserBeanDaoImpl implements BaseDao<UserBean> {

    SQLiteDatabaseHelper myDatabaseHelper;

    public UserBeanDaoImpl(Context context) {
        myDatabaseHelper = new SQLiteDatabaseHelper(context);
    }

    @Override
    public void add(UserBean userBean) {
        SQLiteDatabase sqLiteDatabases = myDatabaseHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        // Start assembling data
        values.put(SQLiteDatabaseHelper.USER_NAME, userBean.getName());
        values.put(SQLiteDatabaseHelper.USER_PASS_WORD, userBean.getPassword());
        values.put(SQLiteDatabaseHelper.USER_PHONE_NUMBER, userBean.getPhoneNumber());
        values.put(SQLiteDatabaseHelper.USER_AGE, userBean.getAge());
        values.put(SQLiteDatabaseHelper.USER_SEX, userBean.getSex());
        values.put(SQLiteDatabaseHelper.USER_NAME, userBean.getName());
        values.put(SQLiteDatabaseHelper.USER_AUTHENTICATION_RESULTS, userBean.getAuthenticationResults());
        values.put(SQLiteDatabaseHelper.USER_AVATAR, userBean.getAvatar());
        values.put(SQLiteDatabaseHelper.USER_ID_NUMBER, userBean.getIdNumber());
        // Insert data
        sqLiteDatabases.insert(SQLiteDatabaseHelper.TABLE_USER, null, values);
        values.clear();
    }

    @Override
    public void delete(int id) {
        SQLiteDatabase sqLiteDatabases=myDatabaseHelper.getWritableDatabase();
        sqLiteDatabases.delete(SQLiteDatabaseHelper.TABLE_USER, SQLiteDatabaseHelper.USER_ID + "=?".new String[]{String.valueOf(id)});

    }

    @Override
    public void update(UserBean userBean) {
        SQLiteDatabase sqLiteDatabases = myDatabaseHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        // Start assembling data
        values.put(SQLiteDatabaseHelper.USER_NAME, userBean.getName());
        values.put(SQLiteDatabaseHelper.USER_PASS_WORD, userBean.getPassword());
        values.put(SQLiteDatabaseHelper.USER_PHONE_NUMBER, userBean.getPhoneNumber());
        values.put(SQLiteDatabaseHelper.USER_AGE, userBean.getAge());
        values.put(SQLiteDatabaseHelper.USER_SEX, userBean.getSex());
        values.put(SQLiteDatabaseHelper.USER_NAME, userBean.getName());
        values.put(SQLiteDatabaseHelper.USER_AUTHENTICATION_RESULTS, userBean.getAuthenticationResults());
        values.put(SQLiteDatabaseHelper.USER_AVATAR, userBean.getAvatar());
        values.put(SQLiteDatabaseHelper.USER_ID_NUMBER, userBean.getIdNumber());

        / / update
        sqLiteDatabases.update(
                SQLiteDatabaseHelper.TABLE_USER
                ,values,
                SQLiteDatabaseHelper.USER_ID + "=?".new String[]{String.valueOf(userBean.getId())});
        values.clear();
    }

    @Override
    public List<UserBean> query(a) {
        List<UserBean> userData=null;
        // The query is Readable and the rest is Writable
        SQLiteDatabase sqLiteDatabases=myDatabaseHelper.getReadableDatabase();
        Cursor cursor=sqLiteDatabases.query(SQLiteDatabaseHelper.TABLE_USER,null.null.null.null.null.null);
        if(cursor.moveToFirst()){
            userData=new ArrayList<>();
            while(cursor.moveToNext()){
                UserBean user=new UserBean();
                int id=cursor.getInt((int) cursor.getColumnIndex(SQLiteDatabaseHelper.USER_ID));
                String name=cursor.getString((int)cursor.getColumnIndex(SQLiteDatabaseHelper.USER_NAME));
                String password=cursor.getString((int)cursor.getColumnIndex(SQLiteDatabaseHelper.USER_PASS_WORD));
                String phoneNumber=cursor.getString((int)cursor.getColumnIndex(SQLiteDatabaseHelper.USER_PHONE_NUMBER));
                String age=cursor.getString((int)cursor.getColumnIndex(SQLiteDatabaseHelper.USER_SEX));
                String sex=cursor.getString((int)cursor.getColumnIndex(SQLiteDatabaseHelper.USER_PASS_WORD));
                String authenticationResults=cursor.getString((int)cursor.getColumnIndex(SQLiteDatabaseHelper.USER_AUTHENTICATION_RESULTS));
                String avatar=cursor.getString((int)cursor.getColumnIndex(SQLiteDatabaseHelper.USER_AVATAR));
                String idNumber=cursor.getString((int)cursor.getColumnIndex(SQLiteDatabaseHelper.USER_ID_NUMBER));

                user.setId(id);
                user.setName(name);
                user.setPassword(password);
                user.setPhoneNumber(phoneNumber);
                user.setAge(age);
                user.setSex(sex);
                user.setAuthenticationResults(authenticationResults);
                user.setAvatar(avatar);
                user.setIdNumber(idNumber);
                userData.add(user);
            }
        }
        cursor.close();
        returnuserData; }}Copy the code

Cursor

A Cursor is a result set Cursor used for random access to a result set. A Cursor receives data retrieved from a database

Cursor to empty

If (cursor.getCount() ==0) if(cursor.getCount() =0)

Then the cursor. MoveToFirst ();

moveToFirst

MoveToFirst () method (used to move the cursor to the first row of the result set, returning false if the result set is empty, true otherwise)

Method to query by user name

public UserBean userNameQuery(String userName) {
        SQLiteDatabase sqLiteDatabases=myDatabaseHelper.getReadableDatabase();
        Cursor cursor=sqLiteDatabases.query(SQLiteDatabaseHelper.TABLE_USER, new String[]{"id"."name"."password"."phoneNumber"."age"."sex"."authenticationResults"."avatar"."idNumber"},"name=? ".new String[]{userName},null.null.null);
        UserBean user=new UserBean();
        if (cursor.getCount() ==0) {return null;
        }

        cursor.moveToFirst();
        int id=cursor.getInt((int) cursor.getColumnIndex(SQLiteDatabaseHelper.USER_ID));
        String name=cursor.getString((int)cursor.getColumnIndex(SQLiteDatabaseHelper.USER_NAME));
        String password=cursor.getString((int)cursor.getColumnIndex(SQLiteDatabaseHelper.USER_PASS_WORD));
        String phoneNumber=cursor.getString((int)cursor.getColumnIndex(SQLiteDatabaseHelper.USER_PHONE_NUMBER));
        String age=cursor.getString((int)cursor.getColumnIndex(SQLiteDatabaseHelper.USER_AGE));
        String sex=cursor.getString((int)cursor.getColumnIndex(SQLiteDatabaseHelper.USER_SEX));
        String authenticationResults=cursor.getString((int)cursor.getColumnIndex(SQLiteDatabaseHelper.USER_AUTHENTICATION_RESULTS));
        String avatar=cursor.getString((int)cursor.getColumnIndex(SQLiteDatabaseHelper.USER_AVATAR));
        String idNumber=cursor.getString((int)cursor.getColumnIndex(SQLiteDatabaseHelper.USER_ID_NUMBER));
        user.setId(id);
        user.setName(name);
        user.setPassword(password);
        user.setPhoneNumber(phoneNumber);
        user.setAge(age);
        user.setSex(sex);
        user.setAuthenticationResults(authenticationResults);
        user.setAvatar(avatar);
        user.setIdNumber(idNumber);

        return user;
    }
Copy the code

Now the database has been written, pay attention to me, the next and login registration actual combat