Android登录和注册用户名密码并连接MySQL8.0完整代码
时间: 2023-06-13 14:03:33 浏览: 110
Android实现登陆注册连接数据库操作完整代码
3星 · 编辑精心推荐
以下是一个简单的 Android 登录和注册示例,连接 MySQL 8.0 数据库。
首先,你需要在 MySQL 中创建一个名为 “users” 的表,其中包含 “id”,“username” 和 “password” 列。
在 Android 项目中,你需要添加以下依赖项:
```gradle
dependencies {
implementation 'com.android.volley:volley:1.2.0'
implementation 'com.google.code.gson:gson:2.8.6'
}
```
接下来,我们开始编写代码。
1. 创建一个名为 “User” 的 Java 类,用于表示数据库中的用户:
```java
public class User {
private int id;
private String username;
private String password;
public User(int id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
public int getId() {
return id;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
}
```
2. 创建一个名为 “MySQLConnector” 的 Java 类,用于连接 MySQL 数据库:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class MySQLConnector {
private static final String URL = "jdbc:mysql://localhost:3306/mydb";
private static final String USER = "root";
private static final String PASSWORD = "password";
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(URL, USER, PASSWORD);
}
}
```
请替换 URL、USER 和 PASSWORD 以匹配你的 MySQL 数据库设置。
3. 创建一个名为 “UserDAO” 的 Java 类,用于处理用户数据:
```java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class UserDAO {
private static final String TABLE_NAME = "users";
private static final String COLUMN_ID = "id";
private static final String COLUMN_USERNAME = "username";
private static final String COLUMN_PASSWORD = "password";
public static boolean createUser(User user) {
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = MySQLConnector.getConnection();
stmt = conn.prepareStatement("INSERT INTO " + TABLE_NAME + " (" + COLUMN_USERNAME + ", " + COLUMN_PASSWORD + ") VALUES (?, ?)");
stmt.setString(1, user.getUsername());
stmt.setString(2, user.getPassword());
stmt.executeUpdate();
return true;
} catch (SQLException e) {
e.printStackTrace();
return false;
} finally {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
public static User getUserByUsername(String username) {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = MySQLConnector.getConnection();
stmt = conn.prepareStatement("SELECT * FROM " + TABLE_NAME + " WHERE " + COLUMN_USERNAME + " = ?");
stmt.setString(1, username);
rs = stmt.executeQuery();
if (rs.next()) {
int id = rs.getInt(COLUMN_ID);
String password = rs.getString(COLUMN_PASSWORD);
return new User(id, username, password);
} else {
return null;
}
} catch (SQLException e) {
e.printStackTrace();
return null;
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
```
4. 创建一个名为 “MainActivity” 的 Java 类,用于处理用户界面和与服务器的通信:
```java
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private static final String BASE_URL = "http://localhost:8080/";
private EditText mUsernameEditText;
private EditText mPasswordEditText;
private Button mLoginButton;
private Button mRegisterButton;
private RequestQueue mRequestQueue;
private Gson mGson;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mUsernameEditText = findViewById(R.id.usernameEditText);
mPasswordEditText = findViewById(R.id.passwordEditText);
mLoginButton = findViewById(R.id.loginButton);
mRegisterButton = findViewById(R.id.registerButton);
mRequestQueue = Volley.newRequestQueue(this);
mGson = new Gson();
mLoginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String username = mUsernameEditText.getText().toString();
String password = mPasswordEditText.getText().toString();
if (username.isEmpty() || password.isEmpty()) {
Toast.makeText(MainActivity.this, "Please enter all fields", Toast.LENGTH_SHORT).show();
return;
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("username", username);
jsonObject.put("password", password);
} catch (JSONException e) {
e.printStackTrace();
return;
}
JsonObjectRequest request = new JsonObjectRequest(
Request.Method.POST,
BASE_URL + "login",
jsonObject,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
boolean success = response.getBoolean("success");
if (success) {
String username = response.getString("username");
Toast.makeText(MainActivity.this, "Welcome, " + username + "!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this, HomeActivity.class);
startActivity(intent);
} else {
Toast.makeText(MainActivity.this, "Login failed, please try again", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(MainActivity.this, "Error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
}
);
mRequestQueue.add(request);
}
});
mRegisterButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String username = mUsernameEditText.getText().toString();
String password = mPasswordEditText.getText().toString();
if (username.isEmpty() || password.isEmpty()) {
Toast.makeText(MainActivity.this, "Please enter all fields", Toast.LENGTH_SHORT).show();
return;
}
User user = new User(0, username, password);
boolean success = UserDAO.createUser(user);
if (success) {
Toast.makeText(MainActivity.this, "Registration successful, please log in", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Registration failed, please try again", Toast.LENGTH_SHORT).show();
}
}
});
}
}
```
请替换 BASE_URL 以匹配你的服务器设置。
在这个示例中,我们使用了 Volley 库来发送 HTTP 请求和接收响应。当用户点击登录按钮时,我们向服务器发送一个包含用户名和密码的 JSON 对象。服务器将检查这些凭据是否有效,并返回一个表示成功或失败的 JSON 响应。如果成功,我们将显示一个欢迎消息,并将用户重定向到主页。否则,我们将显示一个错误消息。
当用户点击注册按钮时,我们将创建一个新的 “User” 对象,并调用 “UserDAO.createUser()” 方法将其插入到数据库中。如果成功,我们将显示一个成功消息,否则我们将显示一个错误消息。
这只是一个简单的示例,你需要根据你的需求进行修改和扩展。
阅读全文