Android开发-SQLite注册登录模块(注册)

  • 前言
  • 数据库的创建
  • 创建实体类
  • 绘制布局
  • 实现功能
  • 效果展示


前言

Android开发中有五种数据储存方式,分别是ShardPreferences、SQLite、ContentProvider、文件存储和网络存储。而SQLite是在项目中经常被采用的,常用于用户信息的存储(安全性待研究),这次写的主要是用户信息的收集,也就是注册啦。

数据库的创建

新建DBOpenHelper继承SQLiteOpenHelper类,重写onCreateonUpgrade这两个方法,然后自定义增删改查四个方法(数据库功底,学习的话推荐廖雪峰老师的SQL教程)。

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

import java.util.ArrayList;



public class DBOpenHelper extends SQLiteOpenHelper {
    /**
     * 声明一个AndroidSDK自带的数据库变量db
     */
    private SQLiteDatabase db;

    /**
     * 写一个这个类的构造函数,参数为上下文context,所谓上下文就是这个类所在包的路径
     * 指明上下文,数据库名,工厂默认空值,版本号默认从1开始
     * super(context,"db_test",null,1);
     * 把数据库设置成可写入状态,除非内存已满,那时候会自动设置为只读模式
     * db = getReadableDatabase();
     */
    public DBOpenHelper(Context context){
        super(context,"db_test",null,1);
        db = getReadableDatabase();
    }

    /**
     * 重写两个必须要重写的方法,因为class DBOpenHelper extends SQLiteOpenHelper
     * 所以就有onCreate()创建表、onUpgrade()删除表两个方法
     */
    @Override
    public void onCreate(SQLiteDatabase db){
        db.execSQL("CREATE TABLE IF NOT EXISTS user(" +
                "_id INTEGER PRIMARY KEY AUTOINCREMENT," +
                "name TEXT," +
                "password TEXT)");
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
        db.execSQL("DROP TABLE IF EXISTS user");
        onCreate(db);
    }
    /**自定义增删改查的四个方法 */
    public void add(String name, String password){
        db.execSQL("INSERT INTO user (name,password) VALUES(?,?)",new Object[]{name,password});
    }
    public void delete(String name, String password){
        db.execSQL("DELETE FROM user WHERE name = AND password ="+name+password);
    }
    public void updata(String password){
        db.execSQL("UPDATE user SET password = ?",new Object[]{password});
    }

    /**
     *  前三个没啥说的,下面重点说一下查询表user全部内容的方法
     * 我们查询出来的内容,需要有个容器存放,以供使用,
     * 所以定义了一个ArrayList类的list容器
     * 这里使用游标Cursor,这就是数据库的功底了,
     * 如果需要用Cursor的话,第一个参数:"表名",中间5个:null,
     * 最后是查询出来内容的排序方式:"name DESC"
     * 游标定义好了,接下来写一个while循环,让游标从表头游到表尾
     * 在游的过程中把游出来的数据存放到list容器中
     */
    public ArrayList<User> getAllData(){

        ArrayList<User> list = new ArrayList<User>();
        Cursor cursor = db.query("user",null,null,null,null,null,"name DESC");
        while(cursor.moveToNext()){
            String name = cursor.getString(cursor.getColumnIndex("name"));
            String password = cursor.getString(cursor.getColumnIndex("password"));
            list.add(new User(name,password));
        }
        return list;
    }
}

创建实体类

学过SSM框架连接数据库的同学应该都知道写,新建User.java,对应数据库中的字段名(namepassword),右键Generate… 点击 Getter and Setter 一键生成get方法,然后在生成toString方法

public class User {
    private String name;            //用户名
    private String password;        //密码
    public User(String name, String password) {
        this.name = name;
        this.password = password;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

绘制布局

新建activity_up.xml,包括用户名+验证码(随机函数)+密码+确认密码+UP按钮等控件。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/res_bg">


<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
<ImageView
    android:id="@+id/back_bt"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:background="@drawable/back"/>
<TextView
    android:layout_width="300dp"
    android:layout_height="50dp"
    android:textSize="15dp"
    android:gravity="center_vertical"
    android:textColor="#FF9D00"
    android:text="已有账号,返回登录?"
    />
</LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#FF9D00">
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
       android:gravity="center_horizontal"
        android:layout_marginTop="100dp"

        >
        <EditText
            android:id="@+id/up_uesr"
            android:layout_width="250dp"
            android:layout_height="50dp"
            android:background="@drawable/login_ed"
            android:textCursorDrawable="@drawable/guangbiao"
            android:hint="用户名"/>
        <LinearLayout
            android:layout_width="250dp"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            >
            <EditText
                android:id="@+id/up_code"
                android:layout_width="125dp"
                android:layout_height="50dp"
                android:hint="验证码"
                android:gravity="center"
                android:layout_marginTop="20dp"
                android:background="@drawable/login_ed"
                android:textCursorDrawable="@drawable/guangbiao"
                />

            <Button
                android:id="@+id/up_codebt"
                android:layout_width="125dp"
                android:layout_height="50dp"
                android:hint="发送验证码"
                android:gravity="center"
                android:layout_marginTop="20dp"
                android:background="@drawable/up_bt"
                android:textCursorDrawable="@drawable/guangbiao"/>

        </LinearLayout>

        <EditText
            android:id="@+id/up_pw"
            android:layout_width="250dp"
            android:layout_height="50dp"
            android:hint="密码"
            android:background="@drawable/login_ed"
            android:textCursorDrawable="@drawable/guangbiao"
            android:inputType="textPassword"
            android:layout_marginTop="20dp"/>

        <EditText
            android:id="@+id/up_pws"
            android:layout_width="250dp"
            android:layout_height="50dp"
            android:hint="密码"
            android:background="@drawable/login_ed"
            android:textCursorDrawable="@drawable/guangbiao"
            android:inputType="textPassword"
            android:layout_marginTop="20dp"/>

        <ImageView
            android:id="@+id/up_login"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:layout_marginTop="20dp"
            android:background="@drawable/log_bt"
            />
    </LinearLayout>


</LinearLayout>

实现功能

验证用户输入是否符合规则,添加入库,伪验证码功能

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

import androidx.appcompat.app.AppCompatActivity;

import java.util.Timer;
import java.util.TimerTask;

public class UpActivity extends AppCompatActivity implements View.OnClickListener {

    EditText userName,password,passwords ,code;
    Button code_bt;
    ImageView back_bt,up_bt;
    DBOpenHelper mDBOpenHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
         /**绑定视图 */
        setContentView(R.layout.activity_up);
        /**数据库对象 */
        mDBOpenHelper = new DBOpenHelper(this);

        /**初始化控件 */
        userName =findViewById( R.id.up_uesr);
        password =findViewById(R.id.up_pw);
        passwords =findViewById(R.id.up_pws);
        code =findViewById(R.id.up_code);
        code_bt =findViewById(R.id.up_codebt);
        back_bt =findViewById(R.id.back_bt);
        up_bt =findViewById(R.id.up_login);

        code_bt.setOnClickListener(this);
        back_bt.setOnClickListener(this);
        up_bt.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
         /**返回登录按钮 */
            case R.id.back_bt:{
                Intent login =new Intent(UpActivity.this, LoginActivity.class);
                startActivity(login);
                finish();
            }
            break;
            /**验证码按钮 */
            case R.id.up_codebt:{
                randomCode();
            }
            break;
            /**注册按钮 */
            case R.id.up_login:{
            /**获取控件内容 */
                String username = userName.getText().toString().trim();
                String pw = password.getText().toString().trim();
                String pws = passwords.getText().toString().trim();
                String phoneCode = passwords.getText().toString().trim();
                if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(pw) && !TextUtils.isEmpty(phoneCode) ) {
                    if (pw.equals(pws)) {
                        //将用户名和密码加入到数据库中
                        mDBOpenHelper.add(username, pw);
                        Intent intent2 = new Intent(this, MainActivity.class);
                        startActivity(intent2);
                        finish();
                        Toast.makeText(this,  "验证通过,注册成功", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(this, "密码不一致,注册失败", Toast.LENGTH_SHORT).show();
                    }
                }else {
                    Toast.makeText(this, "未完善信息,注册失败", Toast.LENGTH_SHORT).show();
                }

            }
            break;
        }


    }
    /**定时生成四位随机函数 */
    private void randomCode() {
        TimerTask delayTask = new TimerTask() {
            @Override
            public void run() {
                String strRand = "";
                for (int i = 0; i < 4; i++) {
                    strRand += String.valueOf((int) (Math.random() * 10));
                }
                code.setText(strRand);
                Log.i("aaa", "randomCode: " + strRand);
            }
        };
        Timer timer = new Timer();
        timer.schedule(delayTask,2000);//延时两秒执行 run 里面的操作

    }
}

效果展示

Android SIP注册及使用 android实现注册功能_sqlite


借鉴所得:…找不到网址了,勿怪


GitHub项目下载得等考试周结束了