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
Như các bài viết về Volley thì bài viết này mình sẽ hướng dẫn các bạn nhận dữ liệu json từ server sử dụng Retrofit 2.
- 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:
3. Thiết kế giao diện:
- 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/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:id="@+id/button"
android:text="@string/btnGet" />
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
- grid_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/cardView"
android:layout_weight="0.8"
android:layout_marginBottom="0dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="9dp"
card_view:cardElevation="0.01dp"
card_view:cardCornerRadius="10dp">
<LinearLayout
android:id="@+id/top_layout"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/img_Thumnail"
android:layout_width="match_parent"
android:layout_height="99dp"
android:scaleType="fitXY" />
<TextView
android:id="@+id/tv_Name"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:layout_gravity="bottom"
android:textColor="@android:color/black"
android:textSize="16dp"
android:typeface="serif"
android:gravity="center_vertical|center" />
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
4. Sử dụng API có sẵn của mình:
Các bạn chú ý phần mình tô đỏ, là cái trường trog table của database, bạn nào chưa biết cách tạo API có thể xem lại bài trước tại đây.
http://dev.androidcoban.com/blog/getallproducts.php
Tiến hành tạo các package và class java như trong cấu trúc.
Tại APIService.java
Hàm này sẽ trả về 1 list các sản phẩm mà API mình gửi xuống.
public interface APIService {
@GET("getallproducts.php")
Call<List<Products>> getAllProduct();
}
Model Products.java
Sử dụng thư viện gson để ánh xạ dữ liệu
com.google.gson.annotations.SerializedName
public class Products implements Serializable {
@SerializedName("id_product")
private int idProduct;
@SerializedName("product_name")
private String productName;
@SerializedName("decription")
private String decription;
@SerializedName("price")
private String price;
@SerializedName("thumnail")
private String thumnail;
// Thêm vào các hàm contructor, getter, setter, toString
}
Tạo adapter để hiển thị dữ liệu : ProductAdapter.java
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ShowHolder> {
private List<Products> productList;
private Context context;
class ShowHolder extends RecyclerView.ViewHolder {
@BindView(R.id.cardView) CardView cardView;
@BindView(R.id.tv_Name) TextView tvProductName;
@BindView(R.id.img_Thumnail) ImageView img_Thumnail;
public ShowHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
public ProductAdapter(List<Products> productList, Context context) {
this.productList = productList;
this.context = context;
}
@Override
public ShowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.grid_item, viewGroup, false);
ShowHolder showHolder= new ShowHolder(view);
return showHolder;
}
@Override
public void onBindViewHolder(ShowHolder showHolder, int i) {
Products product = productList.get(i);
showHolder.tvProductName.setText(product.getProductName());
Glide.with(context).load(product.getThumnail())
.override(150,150).centerCrop().into(showHolder.img_Thumnail);
}
@Override
public int getItemCount() {
return productList.size();
}
}
- Tại Mainactivity.java mình viết hàm để sử dụng APIServer
Hàm này sử dụng link API là:String URL_GET_PRODUCT = "http://dev.androidcoban.com/blog/";
Tại OnRespones nhận dữ liệu tiến hành add vào Arraylist để hiển thị lên View.
private void getAllProduct() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(URL_GET_PRODUCT)
.addConverterFactory(GsonConverterFactory.create())
.build();
APIService apiService = retrofit.create(APIService.class);
Call<List<Products>> call = apiService.getAllProduct();
call.enqueue(new Callback<List<Products>>() {
@Override
public void onResponse(Call<List<Products>> call, Response<List<Products>> response) {
List<Products> productsList = response.body();
for (int i = 0; i<productsList.size() ; i++) {
productList.add(productsList.get(i));
Log.d(TAG, "onResponse" + productsList.get(i).toString());
}
productAdapter.notifyDataSetChanged();
}
@Override
public void onFailure(Call<List<Products>> call, Throwable t) {
Log.e(TAG, "onFailure: " + t.getMessage());
}
});
}
Toàn bộ code của ActivityMain.java
public class MainActivity extends AppCompatActivity {
@BindView(R.id.recycler_view) RecyclerView recyclerview;
RecyclerView.LayoutManager mLayoutManager;
private ArrayList<Products> productList;
private ProductAdapter productAdapter;
String TAG = MainActivity.class.getSimpleName();
String URL_GET_PRODUCT = "http://dev.androidcoban.com/blog/";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
productList = new ArrayList<>();
ButterKnife.bind(this);
addControl();
}
private void addControl() {
recyclerview.setHasFixedSize(true);
// Create 2 col
mLayoutManager = new GridLayoutManager(MainActivity.this, 2);
recyclerview.setLayoutManager(mLayoutManager);
productList = new ArrayList<>();
productAdapter = new ProductAdapter(productList, MainActivity.this);
recyclerview.setAdapter(productAdapter);
}
@OnClick(R.id.button)
public void getProduct() {
getAllProduct();
// productAdapter.notifyDataSetChanged();
}
private void getAllProduct() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(URL_GET_PRODUCT)
.addConverterFactory(GsonConverterFactory.create())
.build();
APIService apiService = retrofit.create(APIService.class);
Call<List<Products>> call = apiService.getAllProduct();
call.enqueue(new Callback<List<Products>>() {
@Override
public void onResponse(Call<List<Products>> call, Response<List<Products>> response) {
List<Products> productsList = response.body();
for (int i = 0; i<productsList.size() ; i++) {
productList.add(productsList.get(i));
Log.d(TAG, "onResponse" + productsList.get(i).toString());
}
productAdapter.notifyDataSetChanged();
}
@Override
public void onFailure(Call<List<Products>> call, Throwable t) {
Log.e(TAG, "onFailure: " + t.getMessage());
}
});
}
}
Nhớ thêm quyền Internet tại Manifest
<uses-permission android:name="android.permission.INTERNET"/>
Cuối cùng chạy và kiểm tra kết quả! Chúc các bạn thành công!



