Android登录和注册用户名密码并连云数据库MySQL详细代码步骤
时间: 2023-06-11 16:08:13 浏览: 221
以下是一个简单的 Android 登录和注册应用程序的基本步骤,包括与 MySQL 数据库的连接:
1.创建一个 MySQL 数据库,用于存储用户信息。在数据库中创建一个名为“users”的表,该表应包含以下字段:id(自增长主键),username,password。
2.在 Android Studio 中创建一个新项目,并添加以下依赖项:
```java
dependencies {
implementation 'com.android.volley:volley:1.1.1'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support:recyclerview-v7:28.0.0'
implementation 'com.android.support:cardview-v7:28.0.0'
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:support-vector-drawable:28.0.0'
}
```
3.在 Android Studio 中创建两个 Activity:LoginActivity 和 RegisterActivity。
4.在 LoginActivity 中,添加一个布局,包括用户名和密码输入框,以及登录按钮。添加一个 OnClickListener,该 OnClickListener 将使用 Volley 库向服务器发送 POST 请求,以验证用户输入的用户名和密码是否正确。如果验证成功,则将用户重定向到主 Activity。
```java
public class LoginActivity extends AppCompatActivity {
private EditText etUsername, etPassword;
private Button btnLogin;
private String url = "http://your-server-url.com/login.php";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
etUsername = findViewById(R.id.et_username);
etPassword = findViewById(R.id.et_password);
btnLogin = findViewById(R.id.btn_login);
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String username = etUsername.getText().toString().trim();
String password = etPassword.getText().toString().trim();
if (TextUtils.isEmpty(username)) {
etUsername.setError("Please enter username");
} else if (TextUtils.isEmpty(password)) {
etPassword.setError("Please enter password");
} else {
login(username, password);
}
}
});
}
private void login(final String username, final String password) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Logging in...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
String message = jsonObject.getString("message");
if (message.equals("success")) {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
} else {
Toast.makeText(LoginActivity.this, "Invalid username or password", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(LoginActivity.this, "Error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("username", username);
params.put("password", password);
return params;
}
};
Volley.newRequestQueue(this).add(stringRequest);
}
}
```
5.在 RegisterActivity 中,添加一个布局,包括用户名、密码和确认密码输入框,以及注册按钮。添加一个 OnClickListener,该 OnClickListener 将使用 Volley 库向服务器发送 POST 请求,以将新用户添加到数据库中。如果注册成功,则将用户重定向到登录页面。
```java
public class RegisterActivity extends AppCompatActivity {
private EditText etUsername, etPassword, etConfirmPassword;
private Button btnRegister;
private String url = "http://your-server-url.com/register.php";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
etUsername = findViewById(R.id.et_username);
etPassword = findViewById(R.id.et_password);
etConfirmPassword = findViewById(R.id.et_confirm_password);
btnRegister = findViewById(R.id.btn_register);
btnRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String username = etUsername.getText().toString().trim();
String password = etPassword.getText().toString().trim();
String confirmPassword = etConfirmPassword.getText().toString().trim();
if (TextUtils.isEmpty(username)) {
etUsername.setError("Please enter username");
} else if (TextUtils.isEmpty(password)) {
etPassword.setError("Please enter password");
} else if (!password.equals(confirmPassword)) {
etConfirmPassword.setError("Passwords do not match");
} else {
register(username, password);
}
}
});
}
private void register(final String username, final String password) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Registering...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
String message = jsonObject.getString("message");
if (message.equals("success")) {
Toast.makeText(RegisterActivity.this, "Registration successful", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
startActivity(intent);
finish();
} else {
Toast.makeText(RegisterActivity.this, "Registration failed", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(RegisterActivity.this, "Error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("username", username);
params.put("password", password);
return params;
}
};
Volley.newRequestQueue(this).add(stringRequest);
}
}
```
6.在服务器上创建两个 PHP 文件,login.php 和 register.php。这些文件将处理 POST 请求,并与 MySQL 数据库进行交互。以下是示例代码:
login.php:
```php
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = $_POST['username'];
$password = $_POST['password'];
require_once('database.php');
$sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$response['message'] = 'success';
} else {
$response['message'] = 'failure';
}
echo json_encode($response);
}
?>
```
register.php:
```php
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = $_POST['username'];
$password = $_POST['password'];
require_once('database.php');
$sql = "INSERT INTO users (username, password) VALUES ('$username', '$password')";
$result = mysqli_query($conn, $sql);
if ($result) {
$response['message'] = 'success';
} else {
$response['message'] = 'failure';
}
echo json_encode($response);
}
?>
```
7.在服务器上创建一个 database.php 文件,用于连接到 MySQL 数据库,并设置以下常量:
```php
<?php
define('DB_HOST', 'your-database-host');
define('DB_USER', 'your-database-username');
define('DB_PASS', 'your-database-password');
define('DB_NAME', 'your-database-name');
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
?>
```
8.在 AndroidManifest.xml 文件中,添加以下权限:
```xml
<uses-permission android:name="android.permission.INTERNET" />
```
9.运行应用程序,并进行测试。
这是一个基本的例子,您可以根据自己的需要进行更改和定制。
阅读全文