Hướng dẫn android retrofit php mysql

Ở part 1 mình đã hướng dẫn các bạn cách tạo web service với php và mysql cho phương thức GET và cách parse json trong android với retrofit. Ở part 2 mình sẽ hướng dẫn các bạn tạo web service cho phương thức POST bằng php và mysql.

Với phương thức GET thì dữ liệu được thấy trên URL thì phương thức POST thì hoàn toàn ngược lại, POST sẽ gửi dữ liệu qua một trường nhập vào trong android và được nhận dạng ở server thông qua tên (name) của các input đó. Chúng ta sẽ thực hiện tiếp với ví dụ ở part 1, các trường nhập vào là name, age, nclass còn id thì mình đã thiết lập tự động tăng trên database nên có thể để null.

Tạo Web Service cho phương thức POST

Để server nhận được dữ liệu bạn gửi từ client android, bạn phải viết phương thức POST bằng web service để server có thể hiểu và nhận thông tin bạn gửi lên. Chúng ta sẽ viết tiếp vào trong file api.php ở part 1

Thêm đoạn code được đánh dấu dưới đây vào file api.php

= 1) {
    while ($row = mysql_fetch_assoc($resouter)) {
        $temparray[] = $row;
    }
}
echo json_encode($temparray);
end:
?>

Mình sẽ giải thích một chút ở đoạn code trên. Từ client (Android) sẽ nhập vào 3 trường name, age, nclass và được nhận dạng ở server thông qua tên của 3 trường này với phương thức POST.

  • Function trim() được sử dụng trim($_POST[“name”]) giống như trong android nó có tác dụng là xóa khoảng trắng của một chuỗi ký tự.
  • Function empty() để kiểm tra nếu chuỗi đó là rỗng thì sẽ thông báo cho người dùng .

Mấy cái bạn có thẻ xử lý trong app android hoặc ở phía sever tùy ý, miễn sao thấy hợp lý là được.

Để kiểm tra hàm POST vừa viết lúc nãy đã được chưa thì bạn sử dụng PostMan mình có giới thiệu ở part 1 để kiểm tra xem nó có hoạt động không.

Hướng dẫn android retrofit php mysql
Kiểm tra phương thức POST web service

  1. Chọn phương thức POST và nhập vào địa chỉ đường dẫn
  2. Chọn tab Body –> chọn tiếp x-www-form-urlencoded
  3. Nhập key và value vào, key phải đúng theo tên của các trường nhận ở server
  4. Bấm Send để xem thông báo trả về, để chắc chắn có được hay không thì bạn vào database xem cho chắc

Hướng dẫn android retrofit php mysql
Thông tin sinh viên vừa thêm hiển thị trong database

Sử dụng phương thức POST với Retrofit trong Android

Để ở phía server nhận được thì bạn cần POST ở client, chúng ta tiếp tục sử dụng retrofit để POST lên.

package com.dev4u.ntc.webservice.webservice;

import com.dev4u.ntc.webservice.models.Student;

import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Query;

/**
 * IDE: Android Studio
 * Created by Nguyen Trong Cong  - NTCDE.COM
 * Name packge: com.dev4u.ntc.webservice.models
 * Name project: WebService
 * Date: 3/24/2017
 * Time: 17:52
 */

public interface APIService {
    // GET students from server
    // Server return json array
    @GET("/student_manager/api.php")
    Call> getStudents();

    // GET student by id student from server
    // Server return json object
    @GET("/student_manager/api.php")
    Call> getStudent(@Query("id") String id);

    // POST student from client to server
    // Server return string
    @FormUrlEncoded
    @POST("/student_manager/api.php")
    Call insertStudent(@Field("name") String name, @Field("age") int age, @Field("nclass") String nclass);
}

Ở client sẽ gửi lên name, age, nclass nên ta dùng @Field của retrofit và phải đi kèm với @FormUrlEncoded , sau khi POST lên thì client nhận về một String thông báo nên ta dùng Call để nhận String.

Viết hàm InsertStudent trong android

Hàm này sẽ gọi hàm insertStudent vừa tạo trong Interface APIService và truyền vào name, age, nclass để post lên server.

    private void insertStudent(String name, int age, String nclass) {
        mAPIService.insertStudent(name, age, nclass).enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                try {
                    String status = response.body().string().toString().trim();
                    Log.e("response", status);
                    if (status.length() > 0) {
                        getAllStudents();
                        Toast.makeText(getBaseContext(), status, Toast.LENGTH_LONG).show();
                    } else {
                        tvResult.setText(response.body().string());
                    }
                } catch (Exception e) {
                    Log.e("onResponse", "Error");
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call call, Throwable t) {
                Log.e("onFailure", t.toString());
            }
        });
    }

Mình chỉnh sửa activity_main.xml một chút, cho nó thêm một cái Button, khi bấm vào button sẽ hiển thị một Custom Dialog nhập vào các trường cần thiết, bạn có thể xem qua bài viết Hướng dẫn Custom Dialog sử dụng XML Layout trong Android

    private void displayInsertDialog() {
        LayoutInflater inflater = getLayoutInflater();
        View alertLayout = inflater.inflate(R.layout.layout_custom_dialog, null);
        final EditText edStudentName, edStudentAge, edStudentClass;
        edStudentName = (EditText) alertLayout.findViewById(R.id.edName);
        edStudentAge = (EditText) alertLayout.findViewById(R.id.edAge);
        edStudentClass = (EditText) alertLayout.findViewById(R.id.edClass);

        AlertDialog.Builder alert = new AlertDialog.Builder(this)
                .setTitle("Insert a new student")
                .setView(alertLayout)
                .setCancelable(false)
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(getBaseContext(), "Cancel", Toast.LENGTH_SHORT).show();
                    }
                })
                .setPositiveButton("Insert", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // code for insert student
                        String name = edStudentName.getText().toString();
                        String age = edStudentAge.getText().toString();
                        String nclass = edStudentClass.getText().toString();
                        if ("".equals(name) || "".equals(age) || "".equals(nclass)) {
                            Toast.makeText(MainActivity.this, "Vui lòng nhập đầy đủ thông tin", Toast.LENGTH_LONG).show();
                        } else insertStudent(name, Integer.parseInt(age), nclass);
                    }
                });
        alert.create().show();
    }

Hướng dẫn android retrofit php mysql
Custom Dialog sử dụng XML Layout trong Android

Để xem chi tiết hơn bạn có thể download mã nguồn mình để ở cuối bài viết.

Qua Part 2 Hướng dẫn tạo Web Service bằng PHP và MYSQL cho ứng dụng di động này bạn có thể hiểu đơn giản về cách tạo web service cho android cũng như cách tạo phương thức POST, GET ở server và cả ở client, sử dụng retrofit để parse json và get dữ liệu từ sever cũng như post dữ liệu từ android đến server.

Bài viết còn hơi loằng ngoằng và ngôn từ chưa được mạch lạc lắm, mong các bạn bạn có thể bỏ qua :D. Xin chân thành cảm ơn các bạn đã ghé xem blog của mình.

Project on Github: https://github.com/trongcong/WebServiceAndroid