Android implements login and registration functions

1. Project Introduction

Connect to the cloud database MySQL to implement the user login and registration function.
Layout: Adopt LinearLayout linear layout and RelativeLayout relative layout.
In terms of code:
1. Use multi-threading: declare the class that implements the Runnable interface, rewrite the run method, instantiate the Runnable implementation class object, pass it into the constructor of a thread, and start the thread (.start()).
2. Access the database through JDBC: register the driver, obtain the connection, obtain the statement execution object, execute the SQL statement, process the result set, and release the resource.

2. Android realizes the login and registration function

1. Database connection and disconnection class

MySQLConnection.java
1. Register driver: The JDBC specification defines the driver interface as java.sql.Driver, and the MySQL driver package provides the implementation class com.mysql.jdbc.Driver. During development, use Class.forName() to load a string description The driver class com.mysql.jdbc.Driver
loads the driver code: Class.forName(“com.mysql.jdbc.Driver”).newInstance();
2. Get the connection: Connection connection=DriverManager.getConnection(“jdbc:mysql:/ /External network address: port/database name", "MySQL user name", "MySQL password");
close connection: connection.close();

public class MySQLConnection {
    
    
    //要连接MySQL数据库的URL    URL_MySQL="jdbc:mysql://外网地址:端口/数据库名称"
    public static final String URL_MySQL="jdbc:mysql://外网地址:端口/数据库名称";
    //要连接MySQL数据库的用户名  NAME_MySQL="MySQL用户名"
    public static final String NAME_MySQL="MySQL用户名";
    //要连接MySQL数据库的密码    PASSWORD_MySQL="MySQL密码"
    public static final String PASSWORD_MySQL="MySQL密码";

    //使用PreparedStatement来执行SQL语句查询
    public static PreparedStatement preparedStatement;
    //使用Resultset接收JDBC查询语句返回的数据集对象
    public static ResultSet resultSet;
    //连接数据库
    public static Connection connection;

    public static void connect()
    {
    
    
        //开启连接数据库
        Log.d("注意","开启连接数据库中......");
        connection=null;
        try {
    
    
            //加载驱动
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            //获取与数据库的连接
            connection= DriverManager.getConnection(URL_MySQL,NAME_MySQL,PASSWORD_MySQL);
        }catch (Exception e){
    
    
            //对异常情况进行处理
            e.printStackTrace();
        }
    }

    public static void close()
    {
    
    
        Log.d("注意","正在关闭数据库连接......");
        try{
    
    
            if(resultSet!=null){
    
    
                resultSet.close();//关闭接收
                resultSet=null;
            }
            if(preparedStatement!=null){
    
    
                preparedStatement.close();//关闭sql语句查询
                preparedStatement=null;
            }
            if(connection!=null){
    
    
                connection.close();//关闭数据库连接
                connection=null;
            }
        }catch (Exception e){
    
    
            //对异常情况进行处理
            e.printStackTrace();
        }
    }
}

2. User information class

User.java

public class User {
    
    
    private String username;
    private String userpassword;

    public User(){
    
    }

    public User(String username,String userpassword)
    {
    
    
        this.username=username;
        this.userpassword=userpassword;
    }

    public String getUsername(){
    
    
        return username;
    }

    public void setUsername(String username) {
    
    
        this.username = username;
    }

    public String getUserpassword() {
    
    
        return userpassword;
    }

    public void setUserpassword(String userpassword) {
    
    
        this.userpassword = userpassword;
    }
}

3. User data operation class

UserDao.java
is here to realize the operation of searching for user name, searching for user name and password.
Registration function: realize the operation of adding user data information to the database
String sql="sql statement";
PreparedStatement preparedStatement=connection.prepareStatement(sql);
here connection is the database connection Object, call the prepareStatement() method through the connection object to obtain the preparedStatement, the execution object of the sql statement, and then call the method to execute the sql statement through the PreparedStatement object.
There are mainly two methods used here

method Results of the
preparedStatement.executeQuery() Execute the select statement and return the query result
preparedStatement.executeUpdate() Execute insert, update, and delete statements, and the return value type is an integer, indicating the number of affected rows

while (resultSet.next())
{ user=new User(); user.setUsername(resultSet.getString(“username”)); user.setUserpassword(resultSet.getString(“userpassword”)); } Use the result set ResultSet here , call the next() method to point to the result set, and return true if the result set is not empty. resultSet.next() points to a row of records




public class UserDao extends MySQLConnection{
    
    
    public User findUserName(String username)
    {
    
    
        connect();
        User user=null;
        try {
    
    
            //sql语句。我这里是根据我自己的users表的username字段来查询记录
            String sql="select * from users where username=?";
            //获取用于向数据库发送sql语句的preparedStatement
            preparedStatement=connection.prepareStatement(sql);
            //根据账号进行查询
            preparedStatement.setString(1,username);
            //执行sql查询语句并返回结果集
            resultSet=preparedStatement.executeQuery();
            while (resultSet.next())
            {
    
    
                //.next()表示指针先下一行,若有数据则返回true
                user=new User();
                user.setUsername(resultSet.getString("username"));
            }
        }catch (Exception e){
    
    
            e.printStackTrace();
        }finally {
    
    
            close();
        }return user;//若传入成功返回账号,失败则为null
    }

    public User findUser(String username,String userpassword)
    {
    
    
        connect();
        User user=null;
        try {
    
    
            //sql语句。我这里是根据我自己的users表的username和password字段来查询记录
            String sql="select * from users where username=? and password=?";
            //获取用于向数据库发送sql语句的preparedStatement
            preparedStatement=connection.prepareStatement(sql);
            //根据账号和密码进行查询
            preparedStatement.setString(1,username);
            preparedStatement.setString(2,userpassword);
            resultSet=preparedStatement.executeQuery();
            while (resultSet.next())
            {
    
    
                user=new User();
                user.setUsername(resultSet.getString("username"));
                user.setUserpassword(resultSet.getString("userpassword"));
            }
        }catch (Exception e){
    
    
            e.printStackTrace();
        }finally {
    
    
            close();
        }return user;//若传入成功返回账号和密码,失败则为null
    }


    public int registerUser(User user)
    {
    
    
        int value=0;
        connect();
        try{
    
    
            String sql="insert into users(username,password) values(?,?)";
            preparedStatement=connection.prepareStatement(sql);
            //将数据插入数据库中
            preparedStatement.setString(1,user.getUsername());
            preparedStatement.setString(2,user.getUserpassword());
            value=preparedStatement.executeUpdate();
        }catch (Exception e){
    
    
            e.printStackTrace();
        }finally {
    
    
            close();
        }return value;
    }
}

4. Login class

4.1 Interface display

login1.png

4.2 Functional description

After entering the user name and password, if they exist, click the login button and return to the main interface after successful login. If they do not exist, a reminder dialog box will pop up and the input box will be cleared; when the input user name, password, user name and password are
empty , a reminder dialog box pops up respectively;
when you click Remember account number and Remember password, and re-enter the login interface, the user name and password still exist, but if the entered user name and password are wrong, the remember function will be cancelled, and the input box will be cleared .

4.3 Main code

activity_login.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    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:background="#66BB"
    tools:context=".LoginActivity">
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/login_background"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:orientation="vertical"
        android:gravity="bottom">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal">
                <TextView
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1"/>
                <TextView
                    android:id="@+id/textview_login"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="登录"
                    android:textSize="25sp"
                    android:textStyle="bold"
                    android:background="@drawable/shape_rectangle_textview"/>
                <TextView
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1"/>
            </LinearLayout>
        </LinearLayout>
        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1">
        </TextView>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_margin="15dp"
                android:orientation="horizontal">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:text="账号:"
                    android:textColor="#000000"
                    android:textStyle="bold"
                    android:textSize="15sp"
                    android:gravity="center"
                    android:background="@drawable/shape_oval_textview"/>
                <EditText
                    android:id="@+id/editText_username"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:inputType="textPassword"
                    android:maxLength="9"
                    android:hint="请输入用户名"
                    android:textColorHint="#999999"
                    android:background="@drawable/shape_round_rectangle"/>
            </LinearLayout>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_margin="15dp"
                android:orientation="horizontal">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:text="密码:"
                    android:textColor="#000000"
                    android:textStyle="bold"
                    android:textSize="15sp"
                    android:gravity="center"
                    android:background="@drawable/shape_oval_textview"/>
                <EditText
                    android:id="@+id/editText_userpassword"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:inputType="numberPassword"
                    android:maxLength="9"
                    android:hint="请输入密码"
                    android:textColorHint="#999999"
                    android:background="@drawable/shape_round_rectangle"/>
            </LinearLayout>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal">
                <TextView
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1"/>
                <CheckBox
                    android:id="@+id/checkbox_remember_id"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:checked="false"
                    android:text="记住账号"
                    android:textColor="#FFC0CB"
                    android:textStyle="bold"
                    android:background="@drawable/shape_rectangle_textview"/>
                <TextView
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1"/>
                <CheckBox
                    android:id="@+id/checkbox_remember_password"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:checked="false"
                    android:text="记住密码"
                    android:textColor="#FFC0CB"
                    android:textStyle="bold"
                    android:background="@drawable/shape_rectangle_textview"/>
                <TextView
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1"/>
            </LinearLayout>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">
                <Button
                    android:id="@+id/button_register_no"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="注册"/>
                <TextView
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1"/>
                <Button
                    android:id="@+id/button_login"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="登录" />
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
</RelativeLayout>

LoginActivity.java

    public void login()
    {
    
    
        EditText editText_username=findViewById(R.id.editText_username);//获取EditText实例
        EditText editText_userpassword=findViewById(R.id.editText_userpassword);//获取EditText实例
        final String username=editText_username.getText().toString().trim();//获取用户输入的用户名
        final String userpassword=editText_userpassword.getText().toString().trim();//获取用户输入的密码
        if(TextUtils.isEmpty(username)&&!TextUtils.isEmpty(userpassword))
        {
    
    
            //弹出提醒对话框,提醒用户用户名不能为空
            AlertDialog.Builder builder=new AlertDialog.Builder(LoginActivity.this);
            builder.setIcon(R.mipmap.ic_launcher);
            builder.setTitle("尊敬的用户");
            builder.setMessage("用户名不能为空,请输入!");
            builder.setPositiveButton("好的",null);
            AlertDialog alertDialog=builder.create();
            alertDialog.show();
            //设计AlertDialog提醒对话框大小
            WindowManager.LayoutParams layoutParams=alertDialog.getWindow().getAttributes();
            layoutParams.width=700;
            layoutParams.height=565;
            alertDialog.getWindow().setAttributes(layoutParams);//设置AlertDialog的宽高
            editText_username.requestFocus();
        }else if (TextUtils.isEmpty(userpassword)&&!TextUtils.isEmpty(username))
        {
    
    
            //弹出提醒对话框,提醒用户密码不能为空
            AlertDialog.Builder builder=new AlertDialog.Builder(LoginActivity.this);
            builder.setIcon(R.mipmap.ic_launcher);
            builder.setTitle("尊敬的用户");
            builder.setMessage("密码不能为空,请输入!");
            builder.setPositiveButton("好的",null);
            AlertDialog alertDialog=builder.create();
            alertDialog.show();
            //设计AlertDialog提醒对话框大小
            WindowManager.LayoutParams layoutParams=alertDialog.getWindow().getAttributes();
            layoutParams.width=700;
            layoutParams.height=565;
            alertDialog.getWindow().setAttributes(layoutParams);//设置AlertDialog的宽高
            editText_userpassword.requestFocus();
        }else if(TextUtils.isEmpty(username)&&TextUtils.isEmpty(userpassword))
        {
    
    
            AlertDialog.Builder builder=new AlertDialog.Builder(LoginActivity.this);
            builder.setIcon(R.mipmap.ic_launcher);
            builder.setTitle("尊敬的用户");
            builder.setMessage("请输入用户名和密码!");
            builder.setPositiveButton("好的",null);
            AlertDialog alertDialog=builder.create();
            alertDialog.show();
            //设计AlertDialog提醒对话框大小
            WindowManager.LayoutParams layoutParams=alertDialog.getWindow().getAttributes();
            layoutParams.width=700;
            layoutParams.height=565;
            alertDialog.getWindow().setAttributes(layoutParams);//设置AlertDialog的宽高
            editText_username.requestFocus();
            editText_userpassword.requestFocus();
        }else
        {
    
    
            //这里要以线程访问,否则会报错
            new Thread(new Runnable() {
    
    
                @Override
                public void run() {
    
    
                    final User user_name=userDao.findUserName(username);
                    final User user=userDao.findUser(username,userpassword);
                    //这里使用Handler类中常用的一个方法,post(Runnable r),立即发送Runnable对象。这里使用已经创建的android.os.Handler对象
                    handler.post(new Runnable() {
    
    
                        @Override
                        public void run() {
    
    
                            if(user_name==null)
                            {
    
    
                                //创建提醒对话框的建造器
                                AlertDialog.Builder builder=new AlertDialog.Builder(LoginActivity.this);
                                //设计对话框标题图标
                                builder.setIcon(R.mipmap.ic_launcher);
                                //设置对话框标题文本
                                builder.setTitle("尊敬的用户");
                                //设置对话框内容文本
                                builder.setMessage("您所输入的账号不存在,请重新输入!");
                                //设置对话框的肯定按钮文本及其点击监听器
                                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
    
    
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
    
    
                                        editText_username.setText("");//清空editText_username内容
                                        editText_userpassword.setText("");//清空editText_userpassword内容
                                        SharedPreferences.Editor editor=sharedPreferences.edit();
                                        editor.putBoolean("ischeckName",false);
                                        editor.putString("username","");
                                        editor.putBoolean("ischeckPassword",false);
                                        editor.putString("userpassword","");
                                        editor.commit();
                                        CheckBox checkbox_remember_id=findViewById(R.id.checkbox_remember_id);//获取CheckBox实例
                                        CheckBox checkbox_remember_password=findViewById(R.id.checkbox_remember_password);//获取CheckBox实例
                                        checkbox_remember_id.setChecked(false);
                                        checkbox_remember_password.setChecked(false);
                                    }
                                });
                                AlertDialog alertDialog=builder.create();//根据建造器构建提醒对话框对象
                                alertDialog.show();//显示提醒对话框
                                //设计AlertDialog提醒对话框大小
                                WindowManager.LayoutParams layoutParams=alertDialog.getWindow().getAttributes();
                                layoutParams.width=700;
                                layoutParams.height=565;
                                alertDialog.getWindow().setAttributes(layoutParams);//设置AlertDialog的宽高
                                return;
                            }
                            if(user==null)
                            {
    
    
                                //创建提醒对话框的建造器
                                AlertDialog.Builder builder=new AlertDialog.Builder(LoginActivity.this);
                                //设计对话框标题图标
                                builder.setIcon(R.mipmap.ic_launcher);
                                //设置对话框标题文本
                                builder.setTitle("尊敬的用户");
                                //设置对话框内容文本
                                builder.setMessage("您所输入的密码错误,请重新输入!");
                                //设置对话框的肯定按钮文本及其点击监听器
                                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
    
    
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
    
    
                                        editText_userpassword.setText("");//清空editText_userpassword内容
                                        SharedPreferences.Editor editor=sharedPreferences.edit();
                                        editor.putBoolean("ischeckName",false);
                                        editor.putString("username","");
                                        editor.putBoolean("ischeckPassword",false);
                                        editor.putString("userpassword","");
                                        editor.commit();
                                        CheckBox checkbox_remember_id=findViewById(R.id.checkbox_remember_id);//获取CheckBox实例
                                        CheckBox checkbox_remember_password=findViewById(R.id.checkbox_remember_password);//获取CheckBox实例
                                        checkbox_remember_id.setChecked(false);
                                        checkbox_remember_password.setChecked(false);
                                    }
                                });
                                AlertDialog alertDialog=builder.create();//根据建造器构建提醒对话框对象
                                alertDialog.show();//显示提醒对话框
                                //设计AlertDialog提醒对话框大小
                                WindowManager.LayoutParams layoutParams=alertDialog.getWindow().getAttributes();
                                layoutParams.width=700;
                                layoutParams.height=565;
                                alertDialog.getWindow().setAttributes(layoutParams);//设置AlertDialog的宽高
                                return;
                            }else
                            {
    
    
                                //如果勾选了"记住账号"复选框,就把账号保存到共享参数里
                                if(isRememberUserName)
                                {
    
    
                                    SharedPreferences.Editor editor=sharedPreferences.edit();//获取编辑器对象
                                    editor.putBoolean("ischeckName",true);
                                    editor.putString("username",editText_username.getText().toString());//添加名为username的账号
                                    editor.commit();//提交编辑器修改
                                }
                                //如果勾选了“记住密码"复选框,就把密码保存到共享参数里
                                if(isRememberUserPassword)
                                {
    
    
                                    SharedPreferences.Editor editor=sharedPreferences.edit();
                                    editor.putBoolean("ischeckPassword",true);
                                    editor.putString("userpassword",editText_userpassword.getText().toString());//添加名为userpassword的密码
                                    editor.commit();
                                }
                                //创建一个意图对象,准备跳转到指定的活动页面
                                Intent intent=new Intent(LoginActivity.this,MainActivity.class);
                                //跳转到意图对象指定的活动页面
                                startActivity(intent);
                            }
                        }
                    });
                }
            }).start();
        }
    }


    //设计读取button按钮点击的功能函数onClick()
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onClick(View v) {
    
    
        if(v.getId()==R.id.button_register_no)
        {
    
    
            //创建一个意图对象,准备跳转到指定的活动页面
            Intent intent=new Intent(this,RegisterActivity.class);
            //跳转到意图对象指定的活动页面
            startActivity(intent);
        }
        if(v.getId()==R.id.button_login)
        {
    
    
            login();
        }
    }

5. Registration class

5.1 Interface display

login2.png

5.2 Functional description

When the entered account already exists in the database, a reminder dialog box will pop up and all input boxes will be cleared. If it does not exist and the subsequent operation is correct, click the registration button to register successfully and return to the login interface; when the entered password and confirm
password If it is different, a reminder dialog box will pop up and the input box will be cleared;
when the input box is empty, a reminder dialog box will pop up;
when you click Show Password or Show Confirmation, the hidden content will be displayed.

5.3 Main code

activity_register.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    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:background="#66BB"
    tools:context=".RegisterActivity">
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:background="@drawable/register_background"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:gravity="bottom">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal">
                <TextView
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1"/>
                <TextView
                    android:id="@+id/textview_register"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="注册"
                    android:textSize="25sp"
                    android:textStyle="bold"
                    android:background="@drawable/shape_rectangle_textview"/>
                <TextView
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1"/>
            </LinearLayout>
        </LinearLayout>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1">
        </TextView>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:layout_marginLeft="15dp"
            android:layout_marginRight="15dp">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal"
                android:layout_marginBottom="7dp">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:text="账号:"
                    android:textColor="#000000"
                    android:textStyle="bold"
                    android:textSize="15sp"
                    android:gravity="center"
                    android:background="@drawable/shape_oval_textview"/>
                <EditText
                    android:id="@+id/editText_username"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:maxLength="9"
                    android:hint="请输入用户名"
                    android:textColorHint="#999999"
                    android:background="@drawable/shape_round_rectangle"/>
            </LinearLayout>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal"
                android:layout_marginBottom="7dp">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:text="密码:"
                    android:textColor="#000000"
                    android:textStyle="bold"
                    android:textSize="15sp"
                    android:gravity="center"
                    android:background="@drawable/shape_oval_textview"/>
                <EditText
                    android:id="@+id/editText_userpassword"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:maxLength="9"
                    android:inputType="numberPassword"
                    android:hint="请输入密码"
                    android:textColorHint="#999999"
                    android:background="@drawable/shape_round_rectangle"/>
            </LinearLayout>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal"
                android:layout_marginBottom="7dp">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:text="确认:"
                    android:textColor="#000000"
                    android:textStyle="bold"
                    android:textSize="15sp"
                    android:gravity="center"
                    android:background="@drawable/shape_oval_textview"/>
                <EditText
                    android:id="@+id/editText_userpassword_define"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:maxLength="9"
                    android:inputType="numberPassword"
                    android:hint="请输入确认密码"
                    android:textColorHint="#999999"
                    android:background="@drawable/shape_round_rectangle"/>
            </LinearLayout>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal">
                <TextView
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1"/>
                <CheckBox
                    android:id="@+id/checkbox_show_password"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:checked="false"
                    android:text="显示密码"
                    android:textColor="#FFC0CB"
                    android:textStyle="bold"
                    android:background="@drawable/shape_rectangle_textview"/>
                <TextView
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1"/>
                <CheckBox
                    android:id="@+id/checkbox_show_password_affirm"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:checked="false"
                    android:text="显示确认"
                    android:textColor="#FFC0CB"
                    android:textStyle="bold"
                    android:background="@drawable/shape_rectangle_textview"/>
                <TextView
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1"/>
            </LinearLayout>
        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <Button
                android:id="@+id/button_return_login"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="返回" />
            <TextView
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"/>
            <Button
                android:id="@+id/button_register_yes"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="确定注册"/>
        </LinearLayout>
    </LinearLayout>
</RelativeLayout>

RegisterActivity.java

    public void register()
    {
    
    
        EditText editText_username=findViewById(R.id.editText_username);//获取EditText实例
        EditText editText_userpassword=findViewById(R.id.editText_userpassword);//获取EditText实例
        EditText editText_userpassword_define=findViewById(R.id.editText_userpassword_define);//获取EditText实例
        final String username=editText_username.getText().toString().trim();//获取用户输入的用户名
        final String userpassword=editText_userpassword.getText().toString().trim();//获取用户输入的密码
        if(TextUtils.isEmpty(username)&&!TextUtils.isEmpty(userpassword))
        {
    
    
            //弹出提醒对话框,提醒用户用户名不能为空
            AlertDialog.Builder builder=new AlertDialog.Builder(RegisterActivity.this);
            builder.setIcon(R.mipmap.ic_launcher);
            builder.setTitle("尊敬的用户");
            builder.setMessage("用户名不能为空,请输入!");
            builder.setPositiveButton("好的",null);
            AlertDialog alertDialog=builder.create();
            alertDialog.show();
            //设计AlertDialog提醒对话框大小
            WindowManager.LayoutParams layoutParams=alertDialog.getWindow().getAttributes();
            layoutParams.width=700;
            layoutParams.height=565;
            alertDialog.getWindow().setAttributes(layoutParams);//设置AlertDialog的宽高
            editText_username.requestFocus();
        }else if (TextUtils.isEmpty(userpassword)&&!TextUtils.isEmpty(username))
        {
    
    
            //弹出提醒对话框,提醒用户密码不能为空
            AlertDialog.Builder builder=new AlertDialog.Builder(RegisterActivity.this);
            builder.setIcon(R.mipmap.ic_launcher);
            builder.setTitle("尊敬的用户");
            builder.setMessage("密码不能为空,请输入!");
            builder.setPositiveButton("好的",null);
            AlertDialog alertDialog=builder.create();
            alertDialog.show();
            //设计AlertDialog提醒对话框大小
            WindowManager.LayoutParams layoutParams=alertDialog.getWindow().getAttributes();
            layoutParams.width=700;
            layoutParams.height=565;
            alertDialog.getWindow().setAttributes(layoutParams);//设置AlertDialog的宽高
            editText_userpassword.requestFocus();
        }else if(TextUtils.isEmpty(username)&&TextUtils.isEmpty(userpassword))
        {
    
    
            AlertDialog.Builder builder=new AlertDialog.Builder(RegisterActivity.this);
            builder.setIcon(R.mipmap.ic_launcher);
            builder.setTitle("尊敬的用户");
            builder.setMessage("请输入用户名和密码!");
            builder.setPositiveButton("好的",null);
            AlertDialog alertDialog=builder.create();
            alertDialog.show();
            //设计AlertDialog提醒对话框大小
            WindowManager.LayoutParams layoutParams=alertDialog.getWindow().getAttributes();
            layoutParams.width=700;
            layoutParams.height=565;
            alertDialog.getWindow().setAttributes(layoutParams);//设置AlertDialog的宽高
            editText_username.requestFocus();
            editText_userpassword.requestFocus();
        }else
        {
    
    
            final User user=new User();
            user.setUsername(username);
            user.setUserpassword(userpassword);
            new Thread(new Runnable() {
    
    
                @Override
                public void run() {
    
    
                    final int value=userDao.registerUser(user);
                    //这里使用Handler类中常用的一个方法,post(Runnable r),立即发送Runnable对象。这里使用已经创建的android.os.Handler对象
                    handler.post(new Runnable() {
    
    
                        @Override
                        public void run() {
    
    
                            //创建一个意图对象,准备跳转到指定的活动页面
                            Intent intent=new Intent(RegisterActivity.this,LoginActivity.class);
                            //跳转到意图对象指定的活动页面
                            startActivity(intent);
                        }
                    });
                }
            }).start();
        }
    }


    //设计读取button按钮点击的功能函数onClick()
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onClick(View v) {
    
    
        if(v.getId()==R.id.button_return_login)
        {
    
    
            //创建一个意图对象,准备跳转到指定的活动页面
            Intent intent=new Intent(this,LoginActivity.class);
            //跳转到意图对象指定的活动页面
            startActivity(intent);
        }
        if(v.getId()==R.id.button_register_yes)
        {
    
    
            EditText editText_username=findViewById(R.id.editText_username);//获取EditText实例
            EditText editText_userpassword=findViewById(R.id.editText_userpassword);//获取EditText实例
            EditText editText_userpassword_define=findViewById(R.id.editText_userpassword_define);//获取EditText实例
            final String username=editText_username.getText().toString().trim();//获取用户输入的用户名
            String password1=editText_userpassword.getText().toString();
            String password2=editText_userpassword_define.getText().toString();
            if(password1.equals(password2))
            {
    
    
                //密码和确认密码相同
                //这里要以线程访问,否则会报错
                new Thread(new Runnable() {
    
    
                    @Override
                    public void run() {
    
    
                        final User user_name=userDao.findUserName(username);
                        //这里使用Handler类中常用的一个方法,post(Runnable r),立即发送Runnable对象。这里使用已经创建的android.os.Handler对象
                        handler.post(new Runnable() {
    
    
                            @Override
                            public void run() {
    
    
                                if(user_name!=null)
                                {
    
    
                                    //创建提醒对话框的建造器
                                    AlertDialog.Builder builder=new AlertDialog.Builder(RegisterActivity.this);
                                    //设计对话框标题图标
                                    builder.setIcon(R.mipmap.ic_launcher);
                                    //设置对话框标题文本
                                    builder.setTitle("尊敬的用户");
                                    //设置对话框内容文本
                                    builder.setMessage("您所输入的账号已存在,请重新输入!");
                                    //设置对话框的肯定按钮文本及其点击监听器
                                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
    
    
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
    
    
                                            editText_username.setText("");//清空editText_username内容
                                            editText_userpassword.setText("");//清空editText_userpassword内容
                                            editText_userpassword_define.setText("");//清空editText_userpassword_define内容
                                        }
                                    });
                                    AlertDialog alertDialog=builder.create();//根据建造器构建提醒对话框对象
                                    alertDialog.show();//显示提醒对话框
                                    //设计AlertDialog提醒对话框大小
                                    WindowManager.LayoutParams layoutParams=alertDialog.getWindow().getAttributes();
                                    layoutParams.width=700;
                                    layoutParams.height=565;
                                    alertDialog.getWindow().setAttributes(layoutParams);//设置AlertDialog的宽高
                                    return;
                                }else
                                {
    
    
                                    register();
                                }
                            }
                        });
                    }
                }).start();
            }else
            {
    
    
                //不同
                //创建提醒对话框的建造器
                AlertDialog.Builder builder=new AlertDialog.Builder(RegisterActivity.this);
                //设计对话框标题图标
                builder.setIcon(R.mipmap.ic_launcher);
                //设置对话框标题文本
                builder.setTitle("尊敬的用户");
                //设置对话框内容文本
                builder.setMessage("密码和确认密码不同,请重新输入!");
                //设置对话框的肯定按钮文本及其点击监听器
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
    
    
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
    
    
                        editText_userpassword.setText("");//清空editText_userpassword内容
                        editText_userpassword_define.setText("");//清空editText_userpassword_define内容
                    }
                });
                AlertDialog alertDialog=builder.create();//根据建造器构建提醒对话框对象
                alertDialog.show();//显示提醒对话框
                //设计AlertDialog提醒对话框大小
                WindowManager.LayoutParams layoutParams=alertDialog.getWindow().getAttributes();
                layoutParams.width=700;
                layoutParams.height=565;
                alertDialog.getWindow().setAttributes(layoutParams);//设置AlertDialog的宽高
                return;
            }
        }
    }

6. Source code download link

GitHub link: Android login and registration function (connecting cloud database MySQL)

3. Summarize

When a program starts for the first time, Android will start a main thread responsible for receiving user input and feedback of operation results, also known as UI thread, creating sub-threads to execute some newly started threads that may cause blocking operations.
Here, a common method post(Runnable r) in the Handler class is used to send the Runnable object immediately, and the Handler can be conveniently used for message delivery.

Guess you like

Origin blog.csdn.net/m0_69101244/article/details/130073280