安卓通過SQLite實現登錄註冊功能(小白式教程)

安卓通過SQLlite實現登錄註冊功能 前面基本操作看圖片











第一個xml文件是:round_bg.xml,後面界面佈局要用到

<" >="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android">    <solid android:color="@color/colorPrimary"/>    <corners android:radius="100dp"/></shape>

第二個xml文件是:round_border.xml

<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android">    <stroke android:color="@color/colorPrimary"        android:width="1dp"/>    <corners android:radius="100dp"/></shape>

修改下系統顏色


改為:

<?xml version="1.0" encoding="utf-8"?><resources>    <color name="colorPrimary">#0099ff    <color name="colorPrimaryDark">#0099ff    <color name="colorAccent">#03DAC5</resources>

現在開始添加圖標:




其他的圖標如下圖,命名方法看個人習慣




可以參考我的命名方法,不要改太多就行。

開始登錄界面的佈局:打開activity_login.xml

<?xml version="1.0" encoding="utf-8"?><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"    tools:context=".LoginActivity">    <androidx.constraintlayout.widget.Guideline        android:id="@+id/guideline"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:orientation="vertical"        app:layout_constraintGuide_percent="0.5" />    <androidx.constraintlayout.widget.Guideline        android:id="@+id/guideline2"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:orientation="horizontal"        app:layout_constraintGuide_percent="0.35" />    <androidx.constraintlayout.widget.Guideline        android:id="@+id/guideline3"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:orientation="horizontal"        app:layout_constraintGuide_percent="0.45" />    <androidx.constraintlayout.widget.Guideline        android:id="@+id/guideline4"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:orientation="horizontal"        app:layout_constraintGuide_percent="0.55" />    <androidx.constraintlayout.widget.Guideline        android:id="@+id/guideline5"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:orientation="horizontal"        app:layout_constraintGuide_percent="0.65" />    <androidx.constraintlayout.widget.Guideline        android:id="@+id/guideline6"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:orientation="horizontal"        app:layout_constraintGuide_percent="0.75" />    <TextView        android:id="@+id/tv_loginview"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/logint"        android:textSize="45sp"        android:textColor="@color/colorPrimary"        app:layout_constraintBottom_toTopOf="@+id/guideline2"        app:layout_constraintEnd_toEndOf="parent"        app:layout_constraintHorizontal_bias="0.129"        app:layout_constraintStart_toStartOf="parent"        app:layout_constraintTop_toTopOf="parent"        app:layout_constraintVertical_bias="0.494" />    <EditText        android:id="@+id/et_User"        android:layout_width="350dp"        android:layout_height="wrap_content"        android:autofillHints="user"        android:background="@drawable/round_border"        android:drawableStart="@drawable/ic_user"        android:drawablePadding="16dp"        android:ems="10"        android:hint="@string/etUser_hint"        android:inputType="textEmailAddress"        android:padding="16dp"        app:layout_constraintBottom_toTopOf="@+id/guideline3"        app:layout_constraintEnd_toEndOf="parent"        app:layout_constraintStart_toStartOf="parent"        tools:ignore="LabelFor"        app:layout_constraintTop_toTopOf="@+id/guideline2" />    <EditText        android:id="@+id/et_Psw"        android:layout_width="350dp"        android:layout_height="wrap_content"        android:autofillHints=""        android:background="@drawable/round_border"        android:drawableStart="@drawable/ic_lock"        android:drawablePadding="16dp"        android:ems="10"        android:hint="@string/pswHint"        android:inputType="textPassword"        android:padding="16dp"        app:layout_constraintBottom_toTopOf="@+id/guideline4"        app:layout_constraintEnd_toEndOf="parent"        app:layout_constraintHorizontal_bias="0.508"        app:layout_constraintStart_toStartOf="parent"        app:layout_constraintTop_toTopOf="@+id/guideline3"        app:layout_constraintVertical_bias="0.47" />    <CheckBox        android:id="@+id/cb_rmbPsw"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:checked="true"        android:drawingCacheQuality="auto"        android:shadowColor="@color/colorPrimaryDark"        android:text="@string/rempsw"        android:textColor="@color/colorPrimary"        android:textColorHighlight="@color/colorPrimary"        android:textColorLink="@color/colorPrimary"        android:textSize="18sp"        app:layout_constraintBottom_toTopOf="@+id/guideline5"        app:layout_constraintEnd_toStartOf="@+id/guideline"        app:layout_constraintStart_toStartOf="parent"        app:layout_constraintTop_toTopOf="@+id/guideline4" />    <Button        android:id="@+id/btn_Login"        android:layout_width="350dp"        android:layout_height="wrap_content"        android:background="@drawable/round_bg"        android:text="@string/logintxt"        android:textColor="#FDFAFA"        android:textSize="18sp"        app:layout_constraintBottom_toTopOf="@+id/guideline6"        app:layout_constraintEnd_toEndOf="parent"        app:layout_constraintHorizontal_bias="0.498"        app:layout_constraintStart_toStartOf="parent"        app:layout_constraintTop_toTopOf="@+id/guideline5"        app:layout_constraintVertical_bias="0.538"  />    <TextView        android:id="@+id/tv_Register"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/yhzc"        android:textColor="@color/colorPrimary"        android:textSize="18sp"        app:layout_constraintBottom_toTopOf="@+id/guideline5"        app:layout_constraintEnd_toEndOf="parent"        app:layout_constraintStart_toStartOf="@+id/guideline"        app:layout_constraintTop_toTopOf="@+id/guideline4" /></androidx.constraintlayout.widget.ConstraintLayout>

註冊界面的佈局:打開activity_registered.xml

<?xml version="1.0" encoding="utf-8"?><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"    tools:context=".RegisteredActivity">    <androidx.constraintlayout.widget.Guideline        android:id="@+id/guideline7"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:orientation="vertical"        app:layout_constraintGuide_percent="0.5" />    <androidx.constraintlayout.widget.Guideline        android:id="@+id/guideline8"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:orientation="horizontal"        app:layout_constraintGuide_percent="0.15" />    <androidx.constraintlayout.widget.Guideline        android:id="@+id/guideline9"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:orientation="horizontal"        app:layout_constraintGuide_percent="0.25" />    <androidx.constraintlayout.widget.Guideline        android:id="@+id/guideline10"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:orientation="horizontal"        app:layout_constraintGuide_percent="0.35" />    <androidx.constraintlayout.widget.Guideline        android:id="@+id/guideline11"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:orientation="horizontal"        app:layout_constraintGuide_percent="0.45" />    <androidx.constraintlayout.widget.Guideline        android:id="@+id/guideline12"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:orientation="horizontal"        app:layout_constraintGuide_percent="0.55" />    <androidx.constraintlayout.widget.Guideline        android:id="@+id/guideline13"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:orientation="horizontal"        app:layout_constraintGuide_percent="0.65" />    <androidx.constraintlayout.widget.Guideline        android:id="@+id/guideline14"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:orientation="horizontal"        app:layout_constraintGuide_percent="0.75" />    <ImageView        android:id="@+id/iv_back"        android:layout_width="50dp"        android:layout_height="50dp"        android:layout_marginTop="16dp"        app:layout_constraintBottom_toTopOf="@+id/guideline8"        app:layout_constraintEnd_toStartOf="@+id/guideline7"        app:layout_constraintHorizontal_bias="0.262"        app:layout_constraintStart_toStartOf="parent"        app:layout_constraintTop_toTopOf="parent"        app:layout_constraintVertical_bias="0.477"        app:srcCompat="@drawable/ic_back" />    <EditText        android:id="@+id/et_rgsName"        android:layout_width="350dp"        android:layout_height="wrap_content"        android:autofillHints=""        android:background="@drawable/round_border"        android:drawableStart="@drawable/ic_user"        android:drawableEnd="@drawable/ic_start"        android:drawablePadding="16dp"        android:ems="10"        android:hint="@string/plsu"        android:inputType="textPersonName"        android:padding="16dp"        app:layout_constraintBottom_toTopOf="@+id/guideline9"        app:layout_constraintEnd_toEndOf="parent"        app:layout_constraintStart_toStartOf="parent"        app:layout_constraintTop_toTopOf="@+id/guideline8" />    <EditText        android:id="@+id/et_rgsEmail"        android:layout_width="350dp"        android:layout_height="wrap_content"        android:autofillHints=""        android:background="@drawable/round_border"        android:drawableStart="@drawable/ic_email"        android:drawablePadding="16dp"        android:ems="10"        android:hint="@string/plsemail"        android:inputType="textPersonName"        android:padding="16dp"        app:layout_constraintBottom_toTopOf="@+id/guideline10"        app:layout_constraintEnd_toEndOf="parent"        app:layout_constraintStart_toStartOf="parent"        app:layout_constraintTop_toTopOf="@+id/guideline9" />    <EditText        android:id="@+id/et_rgsPhoneNum"        android:layout_width="350dp"        android:layout_height="wrap_content"        android:autofillHints=""        android:background="@drawable/round_border"        android:drawableStart="@drawable/ic_phone"        android:drawableEnd="@drawable/ic_start"        android:drawablePadding="16dp"        android:ems="10"        android:hint="@string/plsohone"        android:inputType="textPersonName"        android:padding="16dp"        app:layout_constraintBottom_toTopOf="@+id/guideline11"        app:layout_constraintEnd_toEndOf="parent"        app:layout_constraintStart_toStartOf="parent"        app:layout_constraintTop_toTopOf="@+id/guideline10" />    <EditText        android:id="@+id/et_rgsPsw1"        android:layout_width="350dp"        android:layout_height="wrap_content"        android:autofillHints=""        android:background="@drawable/round_border"        android:drawableStart="@drawable/ic_lock"        android:drawableEnd="@drawable/ic_start"        android:drawablePadding="16dp"        android:ems="10"        android:hint="@string/plspsw"        android:inputType="textPersonName"        android:padding="16dp"        app:layout_constraintBottom_toTopOf="@+id/guideline12"        app:layout_constraintEnd_toEndOf="parent"        app:layout_constraintStart_toStartOf="parent"        app:layout_constraintTop_toTopOf="@+id/guideline11" />    <EditText        android:id="@+id/et_rgsPsw2"        android:layout_width="350dp"        android:layout_height="wrap_content"        android:autofillHints=""        android:background="@drawable/round_border"        android:drawableStart="@drawable/ic_lock"        android:drawableEnd="@drawable/ic_start"        android:drawablePadding="16dp"        android:ems="10"        android:hint="@string/plspsw"        android:inputType="textPersonName"        android:padding="16dp"        app:layout_constraintBottom_toTopOf="@+id/guideline13"        app:layout_constraintEnd_toEndOf="parent"        app:layout_constraintStart_toStartOf="parent"        app:layout_constraintTop_toTopOf="@+id/guideline12" />    <Button        android:id="@+id/btn_rgs"        android:layout_width="350dp"        android:layout_height="wrap_content"        android:background="@drawable/round_bg"        android:text="@string/reg"        android:textColor="#FFFFFF"        android:textSize="18sp"        app:layout_constraintBottom_toTopOf="@+id/guideline14"        app:layout_constraintEnd_toEndOf="parent"        app:layout_constraintHorizontal_bias="0.491"        app:layout_constraintStart_toStartOf="parent"        app:layout_constraintTop_toTopOf="@+id/guideline13"        app:layout_constraintVertical_bias="0.692" /></androidx.constraintlayout.widget.ConstraintLayout>

界面佈局完成,開始來正事。 新建兩個工具類


按確定就能添加:打開DBOpenHelper.class,不懂看註釋!

package com.kizai.com.login;import android.annotation.SuppressLint;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();     */    DBOpenHelper(Context context){        super(context,"db_test",null,1);        db = getReadableDatabase();    }    /**     * 重寫兩個必須要重寫的方法,因為class DBOpenHelper extends SQLiteOpenHelper     * 而這兩個方法是 abstract 類 SQLiteOpenHelper 中聲明的 abstract 方法     * 所以必須在子類 DBOpenHelper 中重寫 abstract 方法     * 想想也是,為啥規定這麼死必須重寫?     * 因為,一個數據庫表,首先是要被創建的,然後免不瞭是要進行增刪改操作的     * 所以就有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," +                "email TEXT," +                "phonenum TEXT)"        );    }    //版本適應    @Override    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){        db.execSQL("DROP TABLE IF EXISTS user");        onCreate(db);    }    /**     * 接下來寫自定義的增刪改查方法     * 這些方法,寫在這裡歸寫在這裡,以後不一定都用     * add()     * delete()     * update()     * getAllData()     */    void add(String name, String password,String email,String phonenum){        db.execSQL("INSERT INTO user (name,password,email,phonenum) VALUES(" >[]{name,password,email,phonenum});    }    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,這就是數據庫的功底瞭,     * 在Android中我就不細說瞭,因為我數據庫功底也不是很厚,     * 但我知道,如果需要用Cursor的話,第一個參數:"表名",中間5個:null,     *                                                     最後是查詢出來內容的排序方式:"name DESC"     * 遊標定義好瞭,接下來寫一個while循環,讓遊標從表頭遊到表尾     * 在遊的過程中把遊出來的數據存放到list容器中     *     */    ArrayList<User> getAllData(){        ArrayList<User> list = new ArrayList<User>();        @SuppressLint("Recycle") Cursor cursor = db.query("user",null,null,null,null,null,"name DESC");        while(cursor.moveToNext()){            String name = cursor.getString(cursor.getColumnIndex("name"));            String email = cursor.getString(cursor.getColumnIndex("email"));            String phonenum = cursor.getString(cursor.getColumnIndex("phonenum"));            String password = cursor.getString(cursor.getColumnIndex("password"));            list.add(new User(name,password,email,phonenum));        }        return list;    }}

再添加一個用戶類:User.class

package com.kizai.com.login;/** * Created by kizai 2020/05/19 */public class User {    private String name;            //用戶名    private String password;        //密碼    private String email;        //郵箱    private String phonenum;        //手機號碼    User(String name, String password, String email, String phonenum) {        this.name = name;        this.password = password;        this.email = email;        this.phonenum = phonenum;    }    public String getEmail() {        return email;    }    public void setEmail(String email) {        this.email = email;    }    public String getPhonenum() {        return phonenum;    }    public void setPhonenum(String phonenum) {        this.phonenum = phonenum;    }    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 + '\'' +                ", email='" + email + '\'' +                ", phonenum='" + phonenum + '\'' +                '}';    }}

打開LoginActivity,裡面有註釋,希望能看懂

package com.kizai.com.login;import androidx.appcompat.app.AppCompatActivity;import android.annotation.SuppressLint;import android.content.Intent;import android.content.SharedPreferences;import android.content.pm.ActivityInfo;import android.os.Bundle;import android.text.TextUtils;import android.text.method.HideReturnsTransformationMethod;import android.text.method.PasswordTransformationMethod;import android.view.View;import android.view.WindowManager;import android.widget.Button;import android.widget.CheckBox;import android.widget.EditText;import android.widget.ImageView;import android.widget.TextView;import android.widget.Toast;import java.util.ArrayList;import java.util.Objects;/** * 此類 implements View.OnClickListener 之後, * 就可以把onClick事件寫到onCreate()方法之外 * 這樣,onCreate()方法中的代碼就不會顯得很冗餘 */public class LoginActivity extends AppCompatActivity implements View.OnClickListener {    private DBOpenHelper mDBOpenHelper;    private EditText et_User, et_Psw;    private CheckBox cb_rmbPsw;    private String userName;    private SharedPreferences.Editor editor;    /**     * 創建 Activity 時先來重寫 onCreate() 方法     * 保存實例狀態     * super.onCreate(savedInstanceState);     * 設置視圖內容的配置文件     * setContentView(R.layout.activity_login);     * 上面這行代碼真正實現瞭把視圖層 View 也就是 layout 的內容放到 Activity 中進行顯示     * 初始化視圖中的控件對象 initView()     * 實例化 DBOpenHelper,待會進行登錄驗證的時候要用來進行數據查詢     * mDBOpenHelper = new DBOpenHelper(this);     */    @SuppressLint("CommitPrefEdits")    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);//隱藏狀態欄        Objects.requireNonNull(getSupportActionBar()).hide();//隱藏標題欄        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);//禁止橫屏        setContentView(R.layout.activity_login);        initView();//初始化界面        mDBOpenHelper = new DBOpenHelper(this);        SharedPreferences sp = getSharedPreferences("user_mes", MODE_PRIVATE);        editor = sp.edit();        if(sp.getBoolean("flag",false)){            String user_read = sp.getString("user","");            String psw_read = sp.getString("psw","");            et_User.setText(user_read);            et_Psw.setText(psw_read);        }    }    private void initView() {        //初始化控件        et_User = findViewById(R.id.et_User);        et_Psw = findViewById(R.id.et_Psw);        cb_rmbPsw = findViewById(R.id.cb_rmbPsw);        Button btn_Login = findViewById(R.id.btn_Login);        TextView tv_register = findViewById(R.id.tv_Register);        //設置點擊事件監聽器        btn_Login.setOnClickListener(this);        tv_register.setOnClickListener(this);    }    @Override    public void onClick(View v) {        switch (v.getId()){            case R.id.tv_Register: //註冊                Intent intent = new Intent(LoginActivity.this, RegisteredActivity.class);//跳轉到註冊界面                startActivity(intent);                finish();                break;            /**             * 登錄驗證:             *             * 從EditText的對象上獲取文本編輯框輸入的數據,並把左右兩邊的空格去掉             *  String name = mEtLoginactivityUsername.getText().toString().trim();             *  String password = mEtLoginactivityPassword.getText().toString().trim();             *  進行匹配驗證,先判斷一下用戶名密碼是否為空,             *  if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(password))             *  再進而for循環判斷是否與數據庫中的數據相匹配             *  if (name.equals(user.getName()) && password.equals(user.getPassword()))             *  一旦匹配,立即將match = true;break;             *  否則 一直匹配到結束 match = false;             *             *  登錄成功之後,進行頁面跳轉:             *             *  Intent intent = new Intent(this, MainActivity.class);             *  startActivity(intent);             *  finish();//銷毀此Activity             */            case R.id.btn_Login:                String name = et_User.getText().toString().trim();                String password = et_Psw.getText().toString().trim();                if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(password)) {                    ArrayList<User> data = mDBOpenHelper.getAllData();                    boolean match = false;                    boolean match2 = false;                    for (int i = 0; i < data.size(); i++) {                        User user = data.get(i);                        if ((name.equals(user.getName()) && password.equals(user.getPassword()))||                                (name.equals(user.getEmail())&&password.equals(user.getPassword()))||                                (name.equals(user.getPhonenum())&&password.equals(user.getPassword()))) {                            userName = user.getName();                            match = true;                            if(cb_rmbPsw.isChecked()){                                editor.putBoolean("flag",true);                                editor.putString("user",user.getName());                                editor.putString("psw",user.getPassword());                                editor.apply();                                match2 = true;                            }else {                                editor.putString("user",user.getName());                                editor.putString("psw","");//                                editor.clear();                                editor.apply();                                match2 = false;                            }                            break;                        } else {                            match = false;                        }                    }                    if (match) {                        if(match2){                            Toast.makeText(this, "成功記住密碼", Toast.LENGTH_SHORT).show();                            cb_rmbPsw.setChecked(true);                        }                        Toast.makeText(this, "登錄成功", Toast.LENGTH_SHORT).show();                        Runnable target;                        //用線程啟動                        Thread thread = new Thread(){                            @Override                            public void run(){                                try {                                    sleep(2000);//2秒 模擬登錄時間                                    String user_name = userName;                                    Intent intent1 = new Intent(LoginActivity.this, MainActivity.class);//設置自己跳轉到成功的界面                                                                        //intent1.putExtra("user_name",user_name);                                    startActivity(intent1);                                    finish();                                }catch (Exception e){                                    e.printStackTrace();                                }                            }                        };                        thread.start();//打開線程                    } else {                        Toast.makeText(this, "用戶名或密碼不正確,請重新輸入", Toast.LENGTH_SHORT).show();                    }                } else {                    Toast.makeText(this, "請輸入你的用戶名或密碼", Toast.LENGTH_SHORT).show();                }                break;        }    }}

打開RegisteredActivity,裡面一樣有註釋

package com.kizai.com.login;import androidx.appcompat.app.AppCompatActivity;import android.content.Intent;import android.content.pm.ActivityInfo;import android.os.Bundle;import android.text.TextUtils;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.ImageView;import android.widget.Toast;public class RegisteredActivity extends AppCompatActivity implements View.OnClickListener {    private EditText et_rgsName, et_rgsEmail, et_rgsPhoneNum, et_rgsPsw1, et_rgsPsw2;    private DBOpenHelper mDBOpenHelper;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);//禁止橫屏        setContentView(R.layout.activity_registered);        setTitle("用戶註冊");//頂部標題改成用戶註冊        initView();//初始化界面        mDBOpenHelper = new DBOpenHelper(this);    }    private void initView() {        et_rgsName = findViewById(R.id.et_rgsName);        et_rgsEmail = findViewById(R.id.et_rgsEmail);        et_rgsPhoneNum = findViewById(R.id.et_rgsPhoneNum);        et_rgsPsw1 = findViewById(R.id.et_rgsPsw1);        et_rgsPsw2 = findViewById(R.id.et_rgsPsw2);        Button btn_register = findViewById(R.id.btn_rgs);        ImageView iv_back = findViewById(R.id.iv_back);        /**         * 註冊頁面能點擊的就三個地方         * top處返回箭頭、刷新驗證碼圖片、註冊按鈕         */        iv_back.setOnClickListener(this);        btn_register.setOnClickListener(this);    }    @Override    public void onClick(View v) {        switch (v.getId()) {            case R.id.iv_back://返回登錄界面                Intent intent = new Intent(RegisteredActivity.this, LoginActivity.class);                startActivity(intent);                finish();                break;            case R.id.btn_rgs://註冊按鈕                //獲取用戶輸入的用戶名、密碼、驗證碼                String username = et_rgsName.getText().toString().trim();                String password1 = et_rgsPsw1.getText().toString().trim();                String password2 = et_rgsPsw2.getText().toString().trim();                String email = et_rgsEmail.getText().toString().trim();                String phonenum = et_rgsPhoneNum.getText().toString().trim();                //註冊驗證                if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(password1) && !TextUtils.isEmpty(password2)) {                    //判斷兩次密碼是否一致                    if (password1.equals(password2)) {                        //將用戶名和密碼加入到數據庫中                        mDBOpenHelper.add(username, password2, email, phonenum);                        Intent intent1 = new Intent(RegisteredActivity.this, LoginActivity.class);                        startActivity(intent1);                        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;        }    }}

做到這裡別以為完事瞭,還要設置打開應用第一個顯示的界面


抄到這裡應該是運行能直接運行成功的,第一次要註冊完才能登錄。

祝你好運!!!寫文章不易麻煩點個贊唄!!!

本文來自網絡,不代表程式碼花園立場,如有侵權,請聯系管理員。https://www.codegarden.cn/article/28048/
返回顶部