2024/03/21(2024春季)

学习时长:5小时

代码行数:300多行

博客数量:1篇

今天完善了个人作业的整个登录注册功能。

package com.example.myapplication;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;

import com.example.myapplication.dphelper.GoalsDbHelper;
import com.example.myapplication.dphelper.RecordDbHelper;
import com.example.myapplication.dphelper.UserDbHelper;
import com.example.myapplication.pojo.User;
import com.example.myapplication.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import pl.com.salsoft.sqlitestudioremote.SQLiteStudioService;

public class MainActivity extends AppCompatActivity {
    private EditText username_v;
    private EditText password_v;
    private TextView message_v;
    private Button turn_teacher;
    private Button login;
    private Button regis;
    private ActivityResultLauncher<Intent> register;
    private CheckBox is_save;
    private CheckBox auto_login;
    private SharedPreferences preferences;
    private static boolean isFirstLaunch = true;//自动登录判断,只使用一次自动登录
    private UserDbHelper userDbHelper;
    private List<User> users;

    @Override
    protected void onStart() {
        super.onStart();
        userDbHelper = UserDbHelper.getInstance(this);
        userDbHelper.openReadLink();
        userDbHelper.openWriteLink();
    }

    @Override
    protected void onStop() {
        userDbHelper.close();
        super.onStop();
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        SQLiteStudioService.instance().start(this);
        init();
        users=new ArrayList<>();
        //带回调的启动activity,将注册成功的账号密码直接返回
        register = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result != null) {

                Intent intent = result.getData();
                if (intent != null && result.getResultCode() == Activity.RESULT_OK) {
                    Bundle bundle = intent.getExtras();
                    User user = (User) bundle.getSerializable("User");
                    String username = user.getUsername();
                    String password = user.getPassword();
                    username_v.setText(username);
                    password_v.setText(password);
                }
            }
        });


        login.setOnClickListener(new View.OnClickListener() {//登录
            @Override
            public void onClick(View v) {
                loginMain();
            }
        });


        regis.setOnClickListener(new View.OnClickListener() {//注册
            @Override
            public void onClick(View v) {
                register.launch(new Intent(MainActivity.this, MainActivityRegis.class));
            }
        });
        turn_teacher.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, MainActivityTeacherMain.class));
            }
        });


        userDbHelper = UserDbHelper.getInstance(this);
        userDbHelper.openReadLink();
        reload();
    }

    private void loginMain() {
        users.clear();
        String username = username_v.getText().toString();
        String password = password_v.getText().toString();
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        mysqllogin(user);
    }

    private void mysqllogin(User user) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Connection coon = null;
                coon = JDBCUtils.getConn();
                String sql = "select * from user where username=? and password=?";
                try {
                    PreparedStatement ps = coon.prepareStatement(sql);
                    ps.setString(1,user.getUsername());
                    ps.setString(2,user.getPassword());
                    ResultSet resultSet=ps.executeQuery();
                    while (resultSet.next())
                    {
                        User user=new User();
                        user.setUsername(resultSet.getString(2));
                        user.setName(resultSet.getString(3));
                        user.setPhone(resultSet.getString(4));
                        user.setClass_no(resultSet.getString(5));
                        users.add(user);
                        Log.d("login", "登录成功");
                    }
                    MainActivity.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (users.isEmpty()) {
                                        Toast toast = Toast.makeText(MainActivity.this, "账号或密码错误", Toast.LENGTH_SHORT);
                                        toast.show();
                                        return;
                                    }
                                    User is_login=users.get(0);
                                    Toast toast = Toast.makeText(MainActivity.this, "登录成功", Toast.LENGTH_SHORT);
                                    toast.show();
                                    Intent intent = new Intent(MainActivity.this, HomeActivity.class);
                                    Bundle bundle = new Bundle();
                                    bundle.putSerializable("user", is_login);
                                    intent.putExtras(bundle);
                                    isFirstLaunch = false;
                                    rememberPassword();
                                    startActivity(intent);
                                }
                            });
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }


    //保存密码
    private void rememberPassword() {
        preferences = getSharedPreferences("user", Context.MODE_PRIVATE);
        if (is_save.isChecked()) {
            SharedPreferences.Editor editor = preferences.edit();
            editor.putString("username", username_v.getText().toString());
            editor.putString("password", password_v.getText().toString());
            editor.putBoolean("isRemember", is_save.isChecked());
            editor.putBoolean("auto_login", auto_login.isChecked());
            editor.commit();
        } else {
            SharedPreferences.Editor editor = preferences.edit();
            editor.putString("username", username_v.getText().toString());
            editor.putString("password", "");
            editor.putBoolean("isRemember", false);
            editor.putBoolean("auto_login", false);
            editor.commit();
        }
    }


    //读取记录的账号密码
    private void reload() {
        preferences = getSharedPreferences("user", Context.MODE_PRIVATE);
        boolean isRemember = preferences.getBoolean("isRemember", false);
        if (isRemember) {
            username_v.setText(preferences.getString("username", ""));
            password_v.setText(preferences.getString("password", ""));
            is_save.setChecked(true);
        }
        boolean autoLogin = preferences.getBoolean("auto_login", false);//自动登录
        if (autoLogin && isFirstLaunch) {
            isFirstLaunch = false;
            auto_login.setChecked(true);
            loginMain();
        }
    }


    //初始化界面
    private void init() {
        username_v = findViewById(R.id.username);
        password_v = findViewById(R.id.password);
        message_v = findViewById(R.id.message);
        login = findViewById(R.id.login);
        regis = findViewById(R.id.regis);
        is_save = findViewById(R.id.is_save);
        auto_login = findViewById(R.id.auto_login);
        turn_teacher=findViewById(R.id.turn_to_teacher);
    }
}
package com.example.myapplication;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.myapplication.dphelper.UserDbHelper;
import com.example.myapplication.pojo.User;
import com.example.myapplication.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class MainActivityRegis extends AppCompatActivity {
    private TextView message_v;
    private EditText username_v;
    private EditText password_v;
    private EditText password2_v;
    private EditText name_v;
    private EditText phone_v;
    private EditText user_class_v;
    private Button regis;
    private UserDbHelper userDbHelper;

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

        regis.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onClick(View v) {
                if(username_v.getText().toString().isEmpty())
                {
                    message_v.setText("用户名不能为空");
                    return;
                }
                if (username_v.getText().toString().length()>20)
                {
                    message_v.setText("用户名长度超过最大限制(20)");
                    return;
                }
                if(name_v.getText().toString().isEmpty())
                {
                    message_v.setText("姓名不能为空");
                    return;
                }
                if (name_v.getText().toString().length()>20)
                {
                    message_v.setText("姓名长度超过最大限制(20)");
                    return;
                }
                if(phone_v.getText().toString().isEmpty())
                {
                    message_v.setText("电话号码不能为空");
                    return;
                }
                if(phone_v.getText().toString().length()!=11)
                {
                    message_v.setText("电话号码格式不正确");
                    return;
                }
                if (user_class_v.getText().toString().length()>20)
                {
                    message_v.setText("班级长度超过最大限制(20)");
                    return;
                }
                if(user_class_v.getText().toString().isEmpty())
                {
                    message_v.setText("班级不能为空");
                    return;
                }
                if (password_v.getText().toString().length()>20)
                {
                    message_v.setText("密码长度超过最大限制(20)");
                    return;
                }
                if(password_v.getText().toString().isEmpty())
                {
                    message_v.setText("密码不能为空");
                    return;
                }
                if(password2_v.getText().toString().isEmpty())
                {
                    message_v.setText("确认密码不能为空");
                    return;
                }
                if(!password_v.getText().toString().equals(password2_v.getText().toString()))
                {
                    message_v.setText("两次密码不一致");
                    return;
                }
                confirm();
            }
        });

    }

    @Override
    protected void onStart() {
        super.onStart();
        userDbHelper= UserDbHelper.getInstance(this);
        userDbHelper.openReadLink();
        userDbHelper.openWriteLink();
    }

    @Override
    protected void onStop() {
        userDbHelper.close();
        super.onStop();

    }

    private long register(User user)
    {
        userDbHelper.openReadLink();
        userDbHelper.openWriteLink();
        System.out.println(userDbHelper);
        return userDbHelper.insert(user);
    }

    private void confirm()
    {
        new AlertDialog.Builder(MainActivityRegis.this)
                .setTitle("确认")
                .setMessage("确认用户名和密码无误并注册?")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        return;
                    }
                })
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        User user=new User();
                        user.setUsername(username_v.getText().toString());
                        user.setName(name_v.getText().toString());
                        user.setPhone(phone_v.getText().toString());
                        user.setClass_no(user_class_v.getText().toString());
                        user.setPassword(password_v.getText().toString());
                        long success=register(user);
                        mysqlregis(user);
                        if(success<0)
                        {
                            Toast toast = Toast.makeText(MainActivityRegis.this, "注册失败,该用户名可能已被使用", Toast.LENGTH_SHORT);
                            toast.show();
                            return;
                        }
                        Toast toast = Toast.makeText(MainActivityRegis.this, "注册成功", Toast.LENGTH_SHORT);
                        toast.show();
                        Intent intent=new Intent();
                        Bundle bundle=new Bundle();
                        bundle.putSerializable("User",user);
                        intent.putExtras(bundle);
                        setResult(MainActivityRegis.RESULT_OK,intent);
                        finish();
                    }
                }).create().show();
    }


    private void mysqlregis(User user) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Connection coon = null;
                coon = JDBCUtils.getConn();
                String sql = "insert into user(username,name,phone,classroom,password) value (?,?,?,?,?)";
                try {
                    PreparedStatement ps = coon.prepareStatement(sql);

                    ps.setString(1,user.getUsername());
                    ps.setString(2,user.getName());
                    ps.setString(3,user.getPhone());
                    ps.setString(4,user.getClass_no());
                    ps.setString(5,user.getPassword());
                    ps.executeUpdate();
                        Log.d("login", "注册成功");
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }
    private void init()
    {
        message_v=findViewById(R.id.message);
        username_v=findViewById(R.id.username);
        password_v=findViewById(R.id.password);
        password2_v=findViewById(R.id.password2);
        regis=findViewById(R.id.regis);
        name_v=findViewById(R.id.name);
        phone_v=findViewById(R.id.phone);
        user_class_v=findViewById(R.id.user_class);
    }

}

 

posted @ 2024-03-21 20:21  伐木工熊大  阅读(6)  评论(0编辑  收藏  举报