Ở 2 bài viết trước mình đã giới thiệu cho các bạn về thư viện volley và xây dựng chức năng đăng nhập sử dụng php/mysql. Các bạn nào chưa xem có thể quay lại xem trước để hiểu hơn.
Ở bài viết này mình sẽ tiếp tục hướng dẫn các bạn cách đăng ký tài khoản.
1.Các bước thực hiện
- Tạo bảng trong database (Các bạn xem ở phần 1)
- Viết trang PHP để đăn ký
- Tạo giao diện đăng ký
- Xử lý đăng ký bằng Volley
- Tạo Activity nhận kết quả trả về
1.1 Tạo bảng account.
1 2 3 4 5 6 7 8 9 10 11 12 |
CREATE TABLE `account`( `user_id` INT PRIMARY KEY AUTO_INCREMENT, `user_name` VARCHAR(50) NOT NULL, `password` VARCHAR(50) NOT NULL, `email` VARCHAR(100) NOT NULL, UNIQUE (user_name) ); INSERT INTO `account`(`user_name`, `password`, `email`) VALUES ('admin','123456','admin@gmail.com' |
1.2 Tạo file PHP để tiến hành đăng ký
- File config kết nối:
1 2 3 4 5 6 7 8 |
<?php $con = mysqli_connect("HOST","USER","PASS","DB_NAME"); //Kết nối database. mysqli_set_charset($con,'utf8'); ?> |
- Tạo file register.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
<?php require_once('dbConnect.php'); mysqli_set_charset($con,'utf8'); /** Array for JSON response*/ $response = array(); if($_SERVER['REQUEST_METHOD'] == 'POST'){ $username = $_POST['username']; $password = $_POST['password']; $email = $_POST['email']; $sqlCheck = "SELECT user_name FROM account WHERE user_name = '$username'"; $result = @mysqli_query($con,$sqlCheck); if (mysqli_num_rows($result) != 0) { $response["success"] = 0; $response["message"] = "Tên đăng nhập đã có người sử dụng!"; } else { $sqlInsert = "INSERT INTO account (user_name,password,email) VALUES ('$username','$password','$email')"; $resultInsert = @mysqli_query($con,$sqlInsert); if ($resultInsert) { $sqlGetInfo = "SELECT user_name, email FROM account WHERE user_name = '$username' AND password = '$password'"; $result = mysqli_query($con,$sqlGetInfo); $row = mysqli_fetch_array($result); $response["success"] = 1; $response["message"] = "Đăng ký thành công!"; $response["user_name"] = $user_name; $response["email"] = $email; } else { $response["success"] = 0; $response["message"] = "Đăng ký thất bại!"; } } /**Return json*/ echo json_encode($response); } ?> |
Tiến hành upload 2 file này lên hosting.
(Lưu ý các bước tiếp theo mình sử dụng lại project trước đó, các bạn lưu ý để tránh gặp lỗi)
1.3 Tạo RegisterActivity.java:
Giao diện XML:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/bg_register" android:gravity="center" android:orientation="vertical" android:padding="10dp" > <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:orientation="vertical" android:paddingLeft="20dp" android:paddingRight="20dp" > <EditText android:id="@+id/editUsername" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginBottom="10dp" android:background="@color/input_register_bg" android:hint="@string/login_lable1" android:padding="10dp" android:inputType="textCapWords" android:textColor="@color/input_register" android:textColorHint="@color/input_register_hint" /> <EditText android:id="@+id/editPassword" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginBottom="10dp" android:background="@color/input_register_bg" android:hint="@string/login_lable2" android:inputType="textPassword" android:padding="10dp" android:textColor="@color/input_register" android:textColorHint="@color/input_register_hint" /> <EditText android:id="@+id/editEmail" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginBottom="10dp" android:background="@color/input_register_bg" android:hint="@string/register_email" android:inputType="textEmailAddress" android:padding="10dp" android:textColor="@color/input_register" android:textColorHint="@color/input_register_hint" /> <!-- Login Button --> <Button android:id="@+id/btnRegister" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="20dip" android:background="#ea4c88" android:text="@string/register_btn" android:textColor="@color/white" /> <!-- Link to Login Screen --> <Button android:id="@+id/btnLogin" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="40dip" android:background="@null" android:text="@string/login_btn" android:textAllCaps="false" android:textColor="@color/white" android:textSize="15dp" /> </LinearLayout> </LinearLayout> |
- Mở build.gradle khai báo thư viện volley:
1 2 3 4 5 |
compile 'com.android.volley:volley:1.0.0' |
- Mở AndroidManifest.xml thêm permistion Internet:
1 2 3 4 5 |
<uses-permission android:name="android.permission.INTERNET"/> |
- Code tại RegisterActivity.java tại đây mình có phân thành các hàm con, và comment đầy đủ cho các bạn.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 |
public class RegisterActivity extends AppCompatActivity { public static final String TAG = RegisterActivity.class.getSimpleName(); private EditText edtUserName; private EditText edtPassWord; private EditText edtEmail; private Button btnRegister; private Button btnLogin; private ProgressDialog pDialog; public static final String REGISTER_URL = "http://dev.androidcoban.com/blog/register.php"; public static final String KEY_USERNAME = "username"; public static final String KEY_PASSWORD = "password"; public static final String KEY_EMAIL = "email"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); addControls(); addEvents(); } private void addEvents() { btnRegister.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Get data input String username = edtUserName.getText().toString().trim(); String password = edtPassWord.getText().toString().trim(); String email = edtEmail.getText().toString().trim(); //Call method register registerUser(username, password, email); } }); btnLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(RegisterActivity.this, LoginActivity.class); startActivity(intent); } }); } private void addControls() { edtUserName = (EditText) findViewById(R.id.editUsername); edtPassWord = (EditText) findViewById(R.id.editPassword); btnRegister = (Button) findViewById(R.id.btnRegister); btnLogin = (Button) findViewById(R.id.btnLogin); edtEmail = (EditText) findViewById(R.id.editEmail); pDialog = new ProgressDialog(this); pDialog.setMessage("Đang đăng ký..."); pDialog.setCanceledOnTouchOutside(false); } /** * Method register * * @param username * @param password * @param email result json */ private void registerUser(final String username, final String password, final String email) { if (checkEditText(edtUserName) && checkEditText(edtPassWord) && checkEditText(edtEmail) && isValidEmail(email)) { pDialog.show(); StringRequest registerRequest = new StringRequest(Request.Method.POST, REGISTER_URL, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d(TAG, response); String message = ""; try { JSONObject jsonObject = new JSONObject(response); if (jsonObject.getInt("success") == 1) { Account account = new Account(); account.setUserName(jsonObject.getString("user_name")); account.setEmail(jsonObject.getString("email")); message = jsonObject.getString("message"); Toast.makeText(RegisterActivity.this, message, Toast.LENGTH_LONG).show(); //Start LoginActivity Intent intent = new Intent(RegisterActivity.this, LoginActivity.class); startActivity(intent); } else { message = jsonObject.getString("message"); Toast.makeText(RegisterActivity.this, message, Toast.LENGTH_LONG).show(); } } catch (JSONException error) { VolleyLog.d(TAG, "Error: " + error.getMessage()); } pDialog.dismiss(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d(TAG, "Error: " + error.getMessage()); pDialog.dismiss(); } }) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<>(); params.put(KEY_USERNAME, username); params.put(KEY_PASSWORD, password); params.put(KEY_EMAIL, email); return params; } }; RequestQueue requestQueue = Volley.newRequestQueue(this); requestQueue.add(registerRequest); } } /** * Check Input */ private boolean checkEditText(EditText editText) { if (editText.getText().toString().trim().length() > 0) return true; else { editText.setError("Vui lòng nhập dữ liệu!"); } return false; } /** * Check Email */ private boolean isValidEmail(String target) { if (target.matches("[a-zA-Z0-9._-]+@[a-z]+.[a-z]+")) return true; else { edtEmail.setError("Email sai định dạng!"); } return false; } } |
Tiến hành chạy project ! Chúc các bạn thành công!
Github: https://github.com/nguyenlinhnttu/LoginVolley