天津储鑫盛钢材现货供应商 发表于 2024-6-15 00:53:12

Android Studio如何通过结合SQLite数据库实现简单的注册,登录功能。

第一步:创建一个活动DatabaseHelper.java;
package com.example.myapplication;

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

public class DatabaseHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "user.db";
    private static final int DATABASE_VERSION = 1;

    private static final String TABLE_USERS = "users";
    private static final String COLUMN_ID = "id";
    private static final String COLUMN_USERNAME = "username";
    private static final String COLUMN_PASSWORD = "password";
    private static final String COLUMN_PHONE_NUMBER = "phone_number";
    private static final String COLUMN_ADDRESS = "address";

    private static final String CREATE_TABLE_USERS =
            "CREATE TABLE " + TABLE_USERS + "(" +
                  COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                  COLUMN_USERNAME + " TEXT NOT NULL UNIQUE, " +
                  COLUMN_PASSWORD + " TEXT NOT NULL, " +
                  COLUMN_PHONE_NUMBER + " TEXT, " +
                  COLUMN_ADDRESS + " TEXT" +
                  ")";

    public DatabaseHelper(Context context) {
      super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

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

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
      db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS);
      onCreate(db);
    }

    /*@SuppressLint("Range")*/

    public long insertUser(String username, String password, String phoneNumber, String address) {
      SQLiteDatabase db = this.getWritableDatabase();

      ContentValues values = new ContentValues();
      values.put(COLUMN_USERNAME, username);
      values.put(COLUMN_PASSWORD, password);
      values.put(COLUMN_PHONE_NUMBER, phoneNumber);
      values.put(COLUMN_ADDRESS, address);

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

      db.close();

      return result;
    }

    public boolean checkUserExist(String username) {
      SQLiteDatabase db = this.getReadableDatabase();

      Cursor cursor = db.query(TABLE_USERS, new String[]{COLUMN_ID},
                COLUMN_USERNAME + "=?", new String[]{username},
                null, null, null);

      boolean exists = cursor.getCount() > 0;

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

      return exists;
    }

    public boolean checkUserExist(String username, String password) {
      SQLiteDatabase db = this.getReadableDatabase();

      Cursor cursor = db.query(TABLE_USERS, new String[]{COLUMN_ID},
                COLUMN_USERNAME + "=? AND " + COLUMN_PASSWORD + "=?",
                new String[]{username, password},
                null, null, null);

      boolean exists = cursor.getCount() > 0;

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

      return exists;
    }
}
第二步:创建一个活动RegisterActivity.java;
package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class RegisterActivity extends AppCompatActivity {

    EditText etUsername, etPassword, etPhoneNumber, etAddress;
    Button btnRegister;

    DatabaseHelper dbHelper;

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

      etUsername = findViewById(R.id.etUsername);
      etPassword = findViewById(R.id.etPassword);
      etPhoneNumber = findViewById(R.id.etPhoneNumber);
      etAddress = findViewById(R.id.etAddress);
      btnRegister = findViewById(R.id.btnRegister);

      dbHelper = new DatabaseHelper(this);

      btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = etUsername.getText().toString();
                String password = etPassword.getText().toString();
                String phoneNumber = etPhoneNumber.getText().toString();
                String address = etAddress.getText().toString();

                if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
                  Toast.makeText(RegisterActivity.this, "用户名和密码不能为空", Toast.LENGTH_SHORT).show();
                  return;
                }

                if (dbHelper.checkUserExist(username)) {
                  Toast.makeText(RegisterActivity.this, "该用户名已被注册", Toast.LENGTH_SHORT).show();
                  return;
                }

                long result = dbHelper.insertUser(username, password, phoneNumber, address);

                if (result != -1) {
                  Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
                  Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                  startActivity(intent);

                } else {
                  Toast.makeText(RegisterActivity.this, "注册失败", Toast.LENGTH_SHORT).show();
                }
            }
      });
    }
}  第三步:创建一个activity_register.xml布局文件;
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >

    <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_gravity="center"
      android:text="注册"
      android:textSize="24sp"
      android:textStyle="bold" />

    <EditText
      android:id="@+id/etUsername"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_margin="16dp"
      android:hint="用户名" />

    <EditText
      android:id="@+id/etPassword"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_margin="16dp"
      android:hint="密码"
      android:inputType="textPassword" />

    <EditText
      android:id="@+id/etPhoneNumber"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_margin="16dp"
      android:hint="电话号码"
      android:inputType="phone" />

    <EditText
      android:id="@+id/etAddress"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_margin="16dp"
      android:hint="地址" />

    <Button
      android:id="@+id/btnRegister"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_gravity="center"
      android:layout_margin="16dp"
      android:text="注册" />

</LinearLayout> 第四步:创建一个活动LoginActivity.java;
该活动登录成功后,会通过代码中的(意图)Intent跳转到MainActivity.java,读者可根据自己的需求更改代码,从而改变跳转的活动文件java的位置。
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class LoginActivity extends AppCompatActivity {

    EditText etUsername, etPassword;
    Button btnLogin;

    DatabaseHelper dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_login);
      etUsername = findViewById(R.id.etUsername);
      etPassword = findViewById(R.id.etPassword);
      btnLogin = findViewById(R.id.btnLogin);
      dbHelper = new DatabaseHelper(this);
      btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = etUsername.getText().toString();
                String password = etPassword.getText().toString();
                if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
                  Toast.makeText(LoginActivity.this, "用户名和密码不能为空", Toast.LENGTH_SHORT).show();
                  return;
                }

                if (dbHelper.checkUserExist(username, password)) {
                  Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();

                        //创建意图
                        Intent intent = new Intent(LoginActivity.this,MainActivity.class);
                        //启动新的activity
                        startActivity(intent);

                } else {
                  Toast.makeText(LoginActivity.this, "用户名或密码不正确", Toast.LENGTH_SHORT).show();
                }
            }
      });
    }
}
第五步:创建一个activity_login.xml布局文件;
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_gravity="center"
      android:text="登录"
      android:textSize="24sp"
      android:textStyle="bold"/>

    <EditText
      android:id="@+id/etUsername"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_margin="16dp"
      android:hint="用户名"/>

    <EditText
      android:id="@+id/etPassword"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_margin="16dp"
      android:hint="密码"
      android:inputType="textPassword"/>
   
    <Button
      android:id="@+id/btnLogin"
      android:layout_width="wrap_content"
      android:layout_height="58dp"
      android:layout_gravity="center"
      android:layout_margin="16dp"
      android:text="登录" />

</LinearLayout> 若完成上述内容,则有下面的运行结果展示:
且注册成功后通过Intent会自动跳转到登录页面:
https://img-blog.csdnimg.cn/direct/6e8bb00af4464468818c28aecd4b97e6.pnghttps://img-blog.csdnimg.cn/direct/fc2a4a0c4f72495f9d56cace2d5cb2ec.png

完成后,可探求‘’user.db”数据库文件的位置所在:
点击右上角View->Tool Windows->Device Exploer出现如下画面:
https://img-blog.csdnimg.cn/direct/dab7e86a219247cf8e482fb37ab4179d.png
点击data->data->"packge包的位置 (活动文件java的代码开头)"->database;可检察到数据库user.db。
https://img-blog.csdnimg.cn/direct/6dea35fb900e410eb0afe6fcf47127bb.png
右键该user.db,选择save as(保存位于电脑某位置)
导入进软件SQLite Expert Personal 5.4(x64)中,即展示如下:
https://img-blog.csdnimg.cn/direct/71c48c7ff6c54423a2b0f4debd1c6d60.png
以上为通过SQLite实现一个简单的注册,登录页面的功能。
若以上存在什么问题,各人可以私信我,大概从评论区说出。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: Android Studio如何通过结合SQLite数据库实现简单的注册,登录功能。