Android開發:使用者註冊登入模組(客戶端+服務端)
阿新 • • 發佈:2018-11-16
1. 前言:
- 為了方便,將註冊頁面和登入頁面也在一塊。演示:
2.資料庫搭建:MySQL
create database test;
use test;
create table user(
user_id int primary key auto_increment,
user_name varchar(10) not null unique,
user_passwd varchar(10) not null);
3.服務端開發:PHP
3.1編寫資料庫連線函式:
<?php $databaseConnection = null; // 建立一個獲取連線函式,用於訪問要訪問伺服器上的資料庫 function getConnection(){ $hostname = "localhost"; //資料庫伺服器的主機名,可以使用IP $database = "test"; $userName = "root"; $password = ""; global $databaseConnection; $databaseConnection = @mysql_connect($hostname, $userName, $password) or die(mysql_error()); mysql_query("set names 'utf-8'"); @mysql_select_db($database, $databaseConnection) or die(mysql_error()); } // 建立一個關閉函式,用於斷開與資料庫的連線 function closeConnection(){ global $databaseConnection; if($databaseConnection){ mysql_close($databaseConnection) or die(mysql_error()); } } ?>
3.2使用者註冊:
<?php session_start(); //啟動PHP會話 $response = array(); //定義JSON響應陣列 include_once ("conn.php"); //連線資料庫 getConnection(); //判斷是否獲取到所需的輸入 if(isset($_POST['user_name']) && isset($_POST['user_passwd'])){ $user_name = $_POST['user_name']; $user_passwd = $_POST['user_passwd']; // 判斷使用者名稱是否佔用 $userNameSQL = "select * from user where user_name = '$user_name'"; $resultSet = mysql_query($userNameSQL); if(mysql_num_rows($resultSet)>0){ $response["success"] = 0; $response["message"] = "Name is used"; // 返回JSON響應 echo json_encode($response); closeConnection(); exit(); } //資料庫插入 $result = mysql_query("insert into user(user_name, user_passwd) values('$user_name', '$user_passwd')"); //判斷插入是否成功 if($result){ // success $response["success"] = 1; $response["message"] = "Successfully created."; echo json_encode($response); } else{ // fail $response["success"] = 0; $response["message"] = "An error occurred."; echo json_encode($response); } } else{ // not input $response["success"] = 0; $response["message"] = "Required fields is missing."; echo json_encode($response); } closeConnection(); ?>
3.3使用者登入:
<?php session_start(); $response = array(); include_once("conn.php"); getConnection(); //判斷是否獲取到非空的輸入 if(isset($_POST['user_name']) && isset($_POST['user_passwd'])){ $user_name = $_POST['user_name']; $user_passwd = $_POST['user_passwd']; //判斷使用者名稱是否登記,且判斷密碼 $userNameSQL = "select * from user where user_name = '$user_name' and user_passwd = '$user_passwd'"; $resultSet = mysql_query($userNameSQL); if(mysql_num_rows($resultSet) > 0){ $user = mysql_fetch_array($resultSet); $_SESSION['user_name'] = $user['user_name']; $_SESSION['user_passwd'] = $user['user_passwd']; $response['success'] = 1; $response["message"] = "Welcome login"; echo json_encode($response); } else{ $response['success'] = 0; $response["message"] = "Wrong user name or password"; echo json_encode($response); } } closeConnection(); ?>
4. Android客戶端開發:
4.1 登入頁面:activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/RelativeLayout1"
android:orientation="vertical"
android:layout_width="300dp"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:gravity="center_horizontal"
tools:context="com.example.study.MainActivity" >
<!--賬號-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="56dp"
android:orientation="horizontal"
android:layout_marginTop="20dp"
android:layout_marginBottom="10dp"
>
<TextView
android:layout_width="34dp"
android:layout_height="30dp"
android:text="賬號:"
android:layout_marginRight="10dp"
/>
<EditText
android:id="@+id/user_name"
android:layout_width="match_parent"
android:layout_height="48dp"
android:hint="請輸入賬號"
/>
</LinearLayout>
<!--密碼-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="56dp"
android:orientation="horizontal"
android:layout_marginBottom="10dp"
>
<TextView
android:layout_width="34dp"
android:layout_height="30dp"
android:text="密碼:"
android:layout_marginRight="10dp"
/>
<EditText
android:id="@+id/user_passwd"
android:layout_width="match_parent"
android:layout_height="48dp"
android:hint="請輸入密碼"
/>
</LinearLayout>
<Button
android:id="@+id/login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="登入"
android:background="#FBE201"
/>
<Button
android:id="@+id/register_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="註冊賬號"
android:background="@null"
android:textColor="#159DFF"
android:layout_gravity="right"
/>
</LinearLayout>
4.2 伺服器訪問類:JSONParser.java
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class JSONParser {
static InputStream is = null; // JSON輸入流
static String json = ""; // 將JSON輸入流轉換為字串
public JSONParser(){
}
//通過HTTP POST方式連線指定的URL
public String makeHttpRequest(String url_string, String method, String param){
HttpURLConnection connection = null;
BufferedReader reader = null;
try{
URL url = new URL(url_string);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(method);
//用輸出流向伺服器發出引數,要求字元,所有不能直接用getOutputStream
DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
dos.writeBytes(param);
dos.flush();
dos.close();
if(connection.getResponseCode() == 200){ // 返回200表示響應成功
is = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
sb.append(line + "\n");
}
is.close();
json = sb.toString();
}
}catch (Exception e){
e.printStackTrace();
}
return json;
}
}
4.3 MainActivity.java
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
public class MainActivity extends AppCompatActivity{
private Button loginBtn;
private Button registerBtn;
private EditText usernameEdit, userpwdEdit;
JSONParser jsonParser = new JSONParser();
private String jsonData; // 伺服器返回值
private String message; // 伺服器返回值
private int success; //伺服器返回值
public static String user_name;
/**
* BaseURL需要改成你們要訪問的ip的地址。
* 如果是在模擬器上使用,要寫10.0.2.2,寫localhost會被認為是模擬器本身。
* 如果是在手機上使用,手機和電腦要在同一區域網,ip地址使用電腦的ipv4,可以在命令列輸出ipconfig檢視。
*/
private static String BaseURL = "http://10.0.2.2/test/";
//註冊地址
private static String url_register = BaseURL + "register.php";
//登入地址
private static String url_login = BaseURL + "login.php";
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//控制元件
loginBtn = findViewById(R.id.login_button);
registerBtn = findViewById(R.id.register_button);
usernameEdit = findViewById(R.id.user_name);
userpwdEdit = findViewById(R.id.user_passwd);
loginBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(usernameEdit.getText().toString().equals("")
|| userpwdEdit.getText().toString().equals("")){
Toast.makeText(getApplicationContext(),
"請輸入賬號密碼", Toast.LENGTH_SHORT).show();
} else{
new Login().execute();
}
}
});
// 為了方便,註冊頁面就不寫了,和 登入頁面 寫在一起
registerBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(usernameEdit.getText().toString().equals("")
|| userpwdEdit.getText().toString().equals("")){
Toast.makeText(getApplicationContext(),
"請輸入賬號密碼", Toast.LENGTH_SHORT).show();
} else{
new Register().execute();
}
}
});
}
/**
* 註冊的後臺非同步任務
*/
class Register extends AsyncTask<String, String, String>{
@Override
protected void onPreExecute() {
super.onPreExecute();
// 可以在此新增顯示一個環形進度條
}
/**
* 開始執行後臺非同步任務
*/
protected String doInBackground(String... args){
String url = url_register;
String name = usernameEdit.getText().toString();
String passwd = userpwdEdit.getText().toString();
try{
// 使用GET方法,是在URL中傳送的。
// 使用POST方法,是在POST請求的HTTP訊息主題中傳送的。
String param = "user_name=" + URLEncoder.encode(name, "UTF-8")
+ "&user_passwd=" + URLEncoder.encode(passwd, "UTF-8");
jsonData = jsonParser.makeHttpRequest(url, "POST", param);
JSONObject jsonObject = new JSONObject(jsonData);
message = jsonObject.getString("message");
success = jsonObject.getInt("success");
} catch (Exception e){
Log.e("log_tag :", e.toString());
}
return null;
}
/**
* 非同步任務完成後給出提示資訊
*/
protected void onPostExecute(String file_url){
String str = "" + success;
Toast.makeText(getApplicationContext(),
"返回碼=" + str + " : " + message, Toast.LENGTH_SHORT).show();
}
}
/**
* 登入的後臺非同步任務
*/
class Login extends AsyncTask<String, String, String>{
@Override
protected void onPreExecute() {
super.onPreExecute();
}
/**
* 開始執行後臺非同步任務
*/
protected String doInBackground(String... args){
String url = url_login;
String name = usernameEdit.getText().toString();
String passwd = userpwdEdit.getText().toString();
try{
String param = "user_name=" + URLEncoder.encode(name, "UTF-8")
+ "&user_passwd=" + URLEncoder.encode(passwd, "UTF-8");
jsonData = jsonParser.makeHttpRequest(url, "POST", param);
JSONObject jsonObject = new JSONObject(jsonData);
message = jsonObject.getString("message");
success = jsonObject.getInt("success");
} catch (Exception e){
Log.e("log_tag :", e.toString());
}
return null;
}
/**
* 非同步任務完成後給出提示資訊
*/
protected void onPostExecute(String file_url){
String str = "" + success;
if(success == 1){
Toast.makeText(getApplicationContext(),
"登入成功", Toast.LENGTH_SHORT).show();
} else{
Toast.makeText(getApplicationContext(),
"返回碼=" + str + " : " + message, Toast.LENGTH_SHORT).show();
}
}
}
}