Gỉa sử ta có đừng dẫn json như sau
http://domain.com/qlvb_mobile/api/ds_donvi
Có nội dung json như sau
{
Ta chuẩn bị 1 class như sau để nhận kết quả trả về:
Hàm lấy json trả về
http://domain.com/qlvb_mobile/api/ds_donvi
Có nội dung json như sau
{
"status": true
"result": "Success"
"data":
}
{
"DV_ID": "10156"
"DV_TEN": "Sở Thông tin và Truyền thông"
}
{
"DV_ID": "2"
"DV_TEN": "Sở Tài nguyên và Môi trường"
}
{
"DV_ID": "3"
"DV_TEN": "Sở Giáo dục và Đào tạo"
}
{
"DV_ID": "4"
"DV_TEN": "Sở Văn hóa - Thể thao và Du lịch"
}Ta chuẩn bị 1 class như sau để nhận kết quả trả về:
| import com.google.gson.annotations.SerializedName; | |
| import java.util.List; | |
| import vn.gov.vn.quanlyvanbansonganh.model.DonVi; | |
| public class DanhSachDonViResult { | |
| @SerializedName("status") | |
| public Boolean status; | |
| @SerializedName("result") | |
| public String message; | |
| public List<DonVi> data; | |
| public Boolean getStatus() { | |
| return status; | |
| } | |
| public void setStatus(Boolean status) { | |
| this.status = status; | |
| } | |
| public String getMessage() { | |
| return message; | |
| } | |
| public void setMessage(String message) { | |
| this.message = message; | |
| } | |
| public List<DonVi> getData() { | |
| return data; | |
| } | |
| public void setData(List<DonVi> data) { | |
| this.data = data; | |
| } | |
| } |
| private void LoadData(){ | |
| // Khởi tại OkhttpClient để lấy dữ liệu | |
| OkHttpClient client = new OkHttpClient(); | |
| Request request = new Request.Builder() | |
| .url(Constant.URL_BASE + Constant.URL_DANH_SACH_DON_VI) | |
| .build(); | |
| // Khởi tạo Gson | |
| final Gson gson = new Gson(); | |
| // Thư thi Request | |
| client.newCall(request).enqueue(new Callback() { | |
| @Override | |
| public void onFailure(Call call, IOException e) { | |
| } | |
| @Override | |
| public void onResponse(Call call, Response response) throws IOException { | |
| String json = response.body().string(); | |
| DanhSachDonViResult danhSachDonViResult = gson.fromJson(json,DanhSachDonViResult.class); | |
| listDonVi = danhSachDonViResult.data; | |
| runOnUiThread(new Runnable() { | |
| @Override | |
| public void run() { | |
| donViAdapter = new DonViAdapter(getApplicationContext(),android.R.layout.simple_list_item_1,listDonVi); | |
| autocompletetextview.setThreshold(1); | |
| autocompletetextview.setAdapter(donViAdapter); | |
| Log.d("listDonVi",listDonVi.toString()); | |
| } | |
| }); | |
| } | |
| }); | |
| } | |
| } |
Nhận xét
Đăng nhận xét