且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从Web获取JSON数据并使用RecyclerView显示

更新时间:2023-02-23 20:29:10

您的数据异步来自服务器.因此,在onCreate()内部,第一次运行应用程序的数据还不是来自服务器,因此在requestQueue.add(stringRequest)下的代码执行时,它在sqlite数据库中也为空.

Your data come from the server asynchronously. So inside onCreate(), at the first time the app run your data is not came from the server yet, so it also empty in your sqlite database when the code under requestQueue.add(stringRequest) execute.

要从服务器添加新数据,请在public void onResponse(String response)内循环遍历服务器中的新项目,进行解析并添加

To add new-fresh data from server, inside public void onResponse(String response) loop through new item from server, parse and add it

for (int i = 0; i < jsonArray.length(); i++) {
     JSONObject jsonObject = jsonArray.getJSONObject(i);
     boolean check = false;
     IDmon = jsonObject.optString("ID").toString();
     IDcuahang = jsonObject.optString("IDCH").toString();
     Tenmon = jsonObject.optString("TenMon").toString();
     Gia = jsonObject.optString("Gia").toString();
     Imgurl = jsonObject.optString("ImgUrl").toString();
     String imgname = Imgurl.substring(Imgurl.lastIndexOf("/") + 1);

     Album a = new Album(abc, IDmon, Tenmon, Gia, imgname, Imgurl);
     albumList.add(a);
     adapter.notifyDataSetChanged();
}