Trước khi băt đầu bài viết để hiểu hơn về retrofit các bạn xem trước các bài viết này:
Tìm Hiểu về Retrofit
Ở bài viết này mình sẽ hướng dẫn các bạn POST dữ liệu từ client lên server sử dụng Retrofit .
Dưới đây là hình ảnh cũng như kết quả
- Chuẩn bị
Mở build.gradle thêm các thư viện sau:
compile 'com.squareup.retrofit2:retrofit:2.0.2' compile 'com.squareup.retrofit2:converter-gson:2.0.2' compile 'com.google.code.gson:gson:2.6.2' //Thư viện butterknife bạn nào chưa biết sử dụng xem bài ở phần đầu compile 'com.jakewharton:butterknife:8.4.0' apt 'com.jakewharton:butterknife-compiler:8.4.0' compile 'com.github.bumptech.glide:glide:3.7.0' compile 'com.android.support:recyclerview-v7:24.2.1' compile 'com.android.support:cardview-v7:24.2.1'
2. Cấu trúc project như sau:
Tương tự bài trước: Tuy nhiên mình có thêm một model để nhận kết quả khi post, nói ở phần bên dưới.
3. Thiết kế giao diện:
<?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:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="serif"
android:text="@string/insertTitle"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Headline" />
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/edtName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/edtName" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/edtDecription"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/edtdecrip" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/edtPrice"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:hint="@string/edtPrice" />
</android.support.design.widget.TextInputLayout>
<Button
android:id="@+id/btnInsert"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="@string/btninsert"
android:textStyle="bold"
android:typeface="serif" />
</LinearLayout>
- Tạo model Message.java
public class Message {
@SerializedName("message")
private String message;
public Message(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
- Viết API bằng PHP
<?php
require_once('dbConnect.php');
mysqli_set_charset($con,'utf8');
$response = array();
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$product_name = $_POST['productName'];
$decription =$_POST['decription'];
$price = $_POST['price'];
$query = "INSERT INTO product(product_name,decription,price)VALUES ('$product_name','$decription','$price')";
if (mysqli_query($con,$query)) {
$response["success"] = 1;
}
} else {
$response["success"] = 0;
}
// echoing JSON response
echo json_encode($response);
?>
- APIService.java
FormUrlEncoded dùng để mã hóa dữ liệu trước khi post
Field (keyname) các giá trị sẽ Post lên ở đây mình post 3 giá trị,
@FormUrlEncoded
@POST("addproduct.php")
Call<Message> insertProduct(
@Field("productName") String product_name,
@Field("decription") String decription,
@Field("price") String price);
- Quay lại InsertActivity.java
Mình tiến hành gọi API và xử lý nhận kết quả trả về là một Message.
public void postRegisterUser(){
String productName = edtName.getText().toString();
String decription = edtDecription.getText().toString();
String price = edtPrice.getText().toString();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(URL_GET_PRODUCT)
.addConverterFactory(GsonConverterFactory.create())
.build();
APIService apiService = retrofit.create(APIService.class);
Call<Message> call = apiService.insertProduct(productName,decription,price);
call.enqueue(new Callback<Message>() {
@Override
public void onResponse(Call<Message> call, Response<Message> response) {
Message message = response.body();
if (message.getMessage().equals("success") ) {
Toast.makeText(getApplicationContext(),"Inserted!" , Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),"Failed!" , Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<Message> call, Throwable t) {
Log.e(TAG, "onFailure: " + t.getMessage());
}
});
}
- Toàn bộ code activity Insert sẽ như sau:
public class InsertActivity extends AppCompatActivity {
@BindView(R.id.edtName) EditText edtName;
@BindView(R.id.edtDecription) EditText edtDecription;
@BindView(R.id.edtPrice) EditText edtPrice;
String URL_GET_PRODUCT = "http://dev.androidcoban.com/blog/";
String TAG = InsertActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert);
ButterKnife.bind(this);
}
@OnClick(R.id.btnInsert)
public void postRegisterUser(){
String productName = edtName.getText().toString();
String decription = edtDecription.getText().toString();
String price = edtPrice.getText().toString();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(URL_GET_PRODUCT)
.addConverterFactory(GsonConverterFactory.create())
.build();
APIService apiService = retrofit.create(APIService.class);
Call<Message> call = apiService.insertProduct(productName,decription,price);
call.enqueue(new Callback<Message>() {
@Override
public void onResponse(Call<Message> call, Response<Message> response) {
Message message = response.body();
if (message.getMessage().equals("success") ) {
Toast.makeText(getApplicationContext(),"Inserted!" , Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),"Failed!" , Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<Message> call, Throwable t) {
Log.e(TAG, "onFailure: " + t.getMessage());
}
});
}
}
Cuối cùng tiến hành run và Kiểm tra!




Bình luận đã bị khoá.