BÀI 4 - ĐỖ DỮ LIỆU VÀO ỨNG DỤNG ANDROID
Video bài học
Đầu tiên, add thư viện Volley vào gradle: implementation 'com.android.volley:volley:1.2.0'
Tiếp theo, tạo một class (getServer) để lấy dữ liệu json theo code bên dưới
public class getServer {
public static String localhost = "192.168.1.4"; // Địa chỉ host wifi.
public static String linkLoaiSanPham = "http://" + localhost + ":8080/ShopRobot/getLoaiSanPham.php"; // Đường dẫn đến php chứa json.
}
Bước 3: Code đổ dữ liệu:
private void getDataLoaiSanPham(){
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext()); // Đọc nội dung url
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(getServer.linkLoaiSanPham, response -> {
if (response != null) {
for (int i=0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
ID = jsonObject.getInt("ID");
tenLoaiSp = jsonObject.getString("tenLoaiSanPham");
hinhAnhLoaiSp = jsonObject.getString("hinhAnhLoaiSanPham");
arrayListLoaiSp.add(new classLoaiSanPham(ID, tenLoaiSp, hinhAnhLoaiSp));
} catch (JSONException e) {
e.printStackTrace();
}
}
arrayListLoaiSp.add(3, new classLoaiSanPham(0, "Liên hệ", "link hình ảnh"));
arrayListLoaiSp.add(4, new classLoaiSanPham(0, "Thông tin", "link hình ảnh"));
adapterLoaiSp.notifyDataSetChanged(); // Cập nhật lại adapter chứa dữ liệu.
}
}, error -> CheckConnection.showToast(getApplicationContext(), error.toString()));
requestQueue.add(jsonArrayRequest); // cập nhật nội dung url vào mảng json.
}