当前位置:网站首页>Android studio login registration - source code (connect to MySQL database)
Android studio login registration - source code (connect to MySQL database)
2022-07-29 05:58:00 【Benben's coriander】
Android Studio Achieve login registration - Source code ( Connect MySql database )
Android Studio Achieve login registration - Source code Two (Servlet + Connect MySql database )


One 、 Create a project
1、 Create a blank project

2、 Name it casually

3、 Set network connection permissions

<uses-permission android:name="android.permission.INTERNET" />
Two 、 introduce Mysql Drive pack
1、 Switch to normal Java engineering

2、 stay libs Introduce MySQL Of jar package
take mysql Copy the driver package of to libs among 

3、 ... and 、 Writing databases and dao as well as JDBC Related codes
1、 Create tables in the database

SQL sentence
/*
Navicat MySQL Data Transfer
Source Server : localhost_3306
Source Server Version : 50562
Source Host : localhost:3306
Source Database : test
Target Server Type : MYSQL
Target Server Version : 50562
File Encoding : 65001
Date: 2021-05-10 17:28:36
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `student`
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`sid` int(11) NOT NULL AUTO_INCREMENT,
`sname` varchar(255) NOT NULL,
`sage` int(11) NOT NULL,
`address` varchar(255) NOT NULL,
PRIMARY KEY (`sid`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of student
-- ----------------------------
INSERT INTO `student` VALUES ('1', 'andi', '21', '21212');
INSERT INTO `student` VALUES ('2', 'a', '2121', '2121');
-- ----------------------------
-- Table structure for `users`
-- ----------------------------
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`uid` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`age` int(255) NOT NULL,
`phone` longblob NOT NULL,
PRIMARY KEY (`uid`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of users
-- ----------------------------
INSERT INTO `users` VALUES ('2', '123', 'HBV Environmental Protection Agency ', '123', '33', 0x3133333333333333333333);
INSERT INTO `users` VALUES ('3', '1233', ' Over and over again ', '1233', '12', 0x3132333333333333333333);
INSERT INTO `users` VALUES ('4', '1244', ' The third generation ', '1244', '12', 0x3133333333333333333333);
INSERT INTO `users` VALUES ('5', '1255', 'SAS', '1255', '33', 0x3133333333333333333333);
2、 stay Android Studio Created in JDBCUtils class
Switching meeting Android View 



Note that the address of the linked database is :jdbc:mysql://10.0.2.2:3306/test
package com.example.myapplication.utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class JDBCUtils {
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConn() {
Connection conn = null;
try {
conn= DriverManager.getConnection("jdbc:mysql://10.0.2.2:3306/test","root","root");
}catch (Exception exception){
exception.printStackTrace();
}
return conn;
}
public static void close(Connection conn){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
3、 establish User Entity class

package com.example.myapplication.entity;
public class User {
private int id;
private String name;
private String username;
private String password;
private int age;
private String phone;
public User() {
}
public User(int id, String name, String username, String password, int age, String phone) {
this.id = id;
this.name = name;
this.username = username;
this.password = password;
this.age = age;
this.phone = phone;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
4、 establish dao Layer and the UserDao

package com.example.myapplication.dao;
import com.example.myapplication.entity.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 UserDao {
public boolean login(String name,String password){
String sql = "select * from users where name = ? and password = ?";
Connection con = JDBCUtils.getConn();
try {
PreparedStatement pst=con.prepareStatement(sql);
pst.setString(1,name);
pst.setString(2,password);
if(pst.executeQuery().next()){
return true;
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
JDBCUtils.close(con);
}
return false;
}
public boolean register(User user){
String sql = "insert into users(name,username,password,age,phone) values (?,?,?,?,?)";
Connection con = JDBCUtils.getConn();
try {
PreparedStatement pst=con.prepareStatement(sql);
pst.setString(1,user.getName());
pst.setString(2,user.getUsername());
pst.setString(3,user.getPassword());
pst.setInt(4,user.getAge());
pst.setString(5,user.getPhone());
int value = pst.executeUpdate();
if(value>0){
return true;
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
JDBCUtils.close(con);
}
return false;
}
public User findUser(String name){
String sql = "select * from users where name = ?";
Connection con = JDBCUtils.getConn();
User user = null;
try {
PreparedStatement pst=con.prepareStatement(sql);
pst.setString(1,name);
ResultSet rs = pst.executeQuery();
while (rs.next()){
int id = rs.getInt(0);
String namedb = rs.getString(1);
String username = rs.getString(2);
String passworddb = rs.getString(3);
int age = rs.getInt(4);
String phone = rs.getString(5);
user = new User(id,namedb,username,passworddb,age,phone);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
JDBCUtils.close(con);
}
return user;
}
}
Four 、 Write pages and Activity Related codes
1、 Write a landing page

<?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=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:layout_editor_absoluteX="219dp"
tools:layout_editor_absoluteY="207dp"
android:padding="50dp"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="15sp"
android:text=" account number :" />
<EditText
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:inputType="textPersonName"
android:text="" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="15sp"
android:text=" password :"
/>
<EditText
android:id="@+id/password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:inputType="textPersonName"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
</LinearLayout>
<Button
android:layout_marginTop="50dp"
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=" Sign in "
android:onClick="login"
/>
<Button
android:id="@+id/button3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="reg"
android:text=" register " />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
effect 
2、 Write the registration page code



<?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=".RegisterActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:layout_editor_absoluteX="219dp"
tools:layout_editor_absoluteY="207dp"
android:padding="50dp"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="15sp"
android:text=" account number :" />
<EditText
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:inputType="textPersonName"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="15sp"
android:text=" nickname :" />
<EditText
android:id="@+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:inputType="textPersonName"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="15sp"
android:text=" password :"
/>
<EditText
android:id="@+id/password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:inputType="textPassword"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="15sp"
android:text=" mobile phone :"
/>
<EditText
android:id="@+id/phone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:inputType="phone"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="15sp"
android:text=" Age :"
/>
<EditText
android:id="@+id/age"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:inputType="number"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
</LinearLayout>
<Button
android:layout_marginTop="50dp"
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=" register "
android:onClick="register"
/>
<Button
android:id="@+id/button3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=" Reset " />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
3、 perfect MainActivity

package com.example.application01;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.example.application01.dao.UserDao;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void reg(View view){
startActivity(new Intent(getApplicationContext(),RegisterActivity.class));
}
public void login(View view){
EditText EditTextname = (EditText)findViewById(R.id.name);
EditText EditTextpassword = (EditText)findViewById(R.id.password);
new Thread(){
@Override
public void run() {
UserDao userDao = new UserDao();
boolean aa = userDao.login(EditTextname.getText().toString(),EditTextpassword.getText().toString());
int msg = 0;
if(aa){
msg = 1;
}
hand1.sendEmptyMessage(msg);
}
}.start();
}
final Handler hand1 = new Handler()
{
@Override
public void handleMessage(Message msg) {
if(msg.what == 1)
{
Toast.makeText(getApplicationContext()," Login successful ",Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext()," Login failed ",Toast.LENGTH_LONG).show();
}
}
};
}
4、 perfect RegisterActivity

package com.example.application01;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.example.application01.dao.UserDao;
import com.example.application01.entity.User;
public class RegisterActivity extends AppCompatActivity {
EditText name = null;
EditText username = null;
EditText password = null;
EditText phone = null;
EditText age = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
name = findViewById(R.id.name);
username = findViewById(R.id.username);
password = findViewById(R.id.password);
phone = findViewById(R.id.phone);
age = findViewById(R.id.age);
}
public void register(View view){
String cname = name.getText().toString();
String cusername = username.getText().toString();
String cpassword = password.getText().toString();
System.out.println(phone.getText().toString());
String cphone = phone.getText().toString();
int cgae = Integer.parseInt(age.getText().toString());
if(cname.length() < 2 || cusername.length() < 2 || cpassword.length() < 2 ){
Toast.makeText(getApplicationContext()," The input information does not meet the requirements. Please re-enter ",Toast.LENGTH_LONG).show();
return;
}
User user = new User();
user.setName(cname);
user.setUsername(cusername);
user.setPassword(cpassword);
user.setAge(cgae);
user.setPhone(cphone);
new Thread(){
@Override
public void run() {
int msg = 0;
UserDao userDao = new UserDao();
User uu = userDao.findUser(user.getName());
if(uu != null){
msg = 1;
}
boolean flag = userDao.register(user);
if(flag){
msg = 2;
}
hand.sendEmptyMessage(msg);
}
}.start();
}
final Handler hand = new Handler()
{
@Override
public void handleMessage(Message msg) {
if(msg.what == 0)
{
Toast.makeText(getApplicationContext()," Registration failed ",Toast.LENGTH_LONG).show();
}
if(msg.what == 1)
{
Toast.makeText(getApplicationContext()," The account already exists , Please change your account number ",Toast.LENGTH_LONG).show();
}
if(msg.what == 2)
{
//startActivity(new Intent(getApplication(),MainActivity.class));
Intent intent = new Intent();
// Use the data you want to transfer putExtra Packaged in intent in
intent.putExtra("a"," Register ");
setResult(RESULT_CANCELED,intent);
finish();
}
}
};
}
5、 ... and 、 Running test results



Android Studio Achieve login registration - Source code ( Connect MySql database )
Android Studio Achieve login registration - Source code Two (Servlet + Connect MySql database )
边栏推荐
- 量化开发必掌握的30个知识点【什么是Level-2数据】
- Synchronous development with open source projects & codereview & pull request & Fork how to pull the original warehouse
- 钉钉告警脚本
- Huawei 2020 school recruitment written test programming questions read this article is enough (Part 1)
- Markdown语法
- The bear market is slow, and bit.store provides stable stacking products to help you get through the bull and bear market
- 并发编程学习笔记 之 工具类Semaphore(信号量)
- DataX installation
- IDEA中设置自动build-改动代码,不用重启工程,刷新页面即可
- 手撕ORM 框架(泛型+注解+反射)
猜你喜欢

July 28 ens/usd Value Forecast: ENS attracts huge profits

Training log 4 of the project "construction of Shandong University mobile Internet development technology teaching website"

Huawei 2020 school recruitment written test programming questions read this article is enough (Part 2)

Semaphore (semaphore) for learning notes of concurrent programming

Tear the ORM framework by hand (generic + annotation + reflection)

Android Studio 实现登录注册-源代码 (连接MySql数据库)

Idea using JDBC to connect mysql database personal detailed tutorial

Move protocol global health declaration, carry out the health campaign to the end

Training log III of "Shandong University mobile Internet development technology teaching website construction" project

“山东大学移动互联网开发技术教学网站建设”项目实训日志七
随机推荐
并发编程学习笔记 之 工具类Semaphore(信号量)
Gluster集群管理小分析
赓续新征程,共驭智存储
量化开发必掌握的30个知识点【什么是分笔逐笔数据】?
Simple optimization of interesting apps for deep learning (suitable for novices)
Training log II of the project "construction of Shandong University mobile Internet development technology teaching website"
北京宝德&TaoCloud共建信创之路
The LAAS protocol of defi 2.0 is the key to revitalizing the development of defi track
我的理想工作,码农的绝对自由支配才是最重要的——未来创业的追求
ReportingService WebService Form身份验证
Machine learning makes character recognition easier: kotlin+mvvm+ Huawei ml Kit
Tear the ORM framework by hand (generic + annotation + reflection)
Move protocol global health declaration, carry out the health campaign to the end
July 28 ens/usd Value Forecast: ENS attracts huge profits
Realize the scheduled backup of MySQL database in Linux environment through simple script (mysqldump command backup)
Huawei 2020 school recruitment written test programming questions read this article is enough (Part 1)
Nailing alarm script
C# 判断用户是手机访问还是电脑访问
浅谈分布式全闪存储自动化测试平台设计
数组的基础使用--遍历循环数组求出数组最大值,最小值以及最大值下标,最小值下标