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

get JSON data from web and display using RecyclerView

我是新手 android,我正在创建应用程序,它从 phpmyadmin 中的 table 获取 json 数据,然后保存在应用程序的数据库中。我读取数据并在 RecyclerView 上显示,但是当我第一次 运行 应用程序时,table 数据库什么都不显示。但是从第二次开始,应用程序可以按我的意愿读取数据和显示。

任何人都可以帮助我第一次 运行 app 第二次。 这是我的代码:

   db.querydata("Create table if not exists tbl_mon_app (_ID integer primary key, IDMon integer not null, IDCH integer not null, TenMon text not null, Gia text not null, ImgUrl text not null, ImgLocal text)");
    Cursor c = db.getdata("select * from tbl_mon_app");
    int count = c.getCount();

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        StringRequest stringRequest = new StringRequest(Request.Method.GET, booking,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        if (response.equals("{\"DSMON\":[]}")) {

                        } else

                            try {
                                JSONObject jsonRootObject = new JSONObject(response);
                                JSONArray jsonArray = jsonRootObject.optJSONArray("DSMON");
                                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);


                                    Cursor ds = db.getdata("select * from tbl_mon_app");
                                    if (ds.moveToFirst()) {
                                        while (!ds.isAfterLast()) {
                                            if (IDmon.equals(ds.getString(ds.getColumnIndex("IDMon")))) {
                                                check = true;
                                                break;
                                            }
                                            ds.moveToNext();
                                        }
                                    }
                                    if (check) {
                                        db.querydata("update tbl_mon_app set IDCH='" + IDcuahang + "', TenMon='" + Tenmon + "', Gia='" + Gia + "', ImgUrl='" + Imgurl + "', ImgLocal='" + "hismart/hinhmon/" + imgname + "' where IDMon='" + IDmon + "'");


                                    } else {
                                        db.querydata("insert into tbl_mon_app values(null,'" + IDmon + "','"

                                                + IDcuahang + "','" + Tenmon + "','" + Gia + "','" + Imgurl + "','" + "hismart/hinhmon/" + imgname + "')");
                                    }
                                    ds.close();
                                }
                                db.close();


                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.d("Lỗi", "Lỗi" + "\n" + error.toString());
                    }
                }
        );
        requestQueue.add(stringRequest);

检查数据库名称:tbl_mon_app 以读取上面添加的数据库:

 Cursor cur = db.getdata("select * from tbl_mon_app");
            if (cur.moveToFirst()) {

                while (!cur.isAfterLast()) {

                     Toast.makeText(BookActivity.this, cur.getString(cur.getColumnIndex("Gia")), Toast.LENGTH_SHORT).show();
                    ArrIDMon.add(cur.getString(cur.getColumnIndex("IDMon")));
                    cur.moveToNext();

                }
            }

            if (cur.moveToFirst()) {

                while (!cur.isAfterLast()) {

                   // Toast.makeText(BookActivity.this, cur.getString(cur.getColumnIndex("TenMon")), Toast.LENGTH_SHORT).show();
                    ArrTenmon.add(cur.getString(cur.getColumnIndex("TenMon")));
                    cur.moveToNext();

                }
            }

            if (cur.moveToFirst()) {

                while (!cur.isAfterLast()) {

                    // Toast.makeText(BookActivity.this, cur.getString(cur.getColumnIndex("Gia")), Toast.LENGTH_SHORT).show();
                    ArrGia.add(cur.getString(cur.getColumnIndex("Gia")));
                    cur.moveToNext();

                }
            }
            if (cur.moveToFirst()) {

                while (!cur.isAfterLast()) {

                    // Toast.makeText(BookActivity.this, cur.getString(cur.getColumnIndex("Gia")), Toast.LENGTH_SHORT).show();
                    ArrImgUrl.add(cur.getString(cur.getColumnIndex("ImgUrl")));
                    cur.moveToNext();

                }
            }

            if (cur.moveToFirst()) {

                while (!cur.isAfterLast()) {

                    // Toast.makeText(BookActivity.this, cur.getString(cur.getColumnIndex("Gia")), Toast.LENGTH_SHORT).show();
                    ArrImgLocal.add(cur.getString(cur.getColumnIndex("ImgLocal")));
                    cur.moveToNext();

                }
            }

将数据添加到数组列表并设置通知数据集已更改

    String abc = MainActivity.resultQR.getContents();
    Toast.makeText(this, String.valueOf(count), Toast.LENGTH_SHORT).show();

    // add data to arraylist
    for (int i = 0; i < count; i++) {

        Album a = new Album(abc, ArrIDMon.get(i), ArrTenmon.get(i), ArrGia.get(i), ArrImgLocal.get(i), ArrImgUrl.get(i));
        albumList.add(a);
        adapter.notifyDataSetChanged();
    }

    cur.close();

}

这是 Recycleview 适配器

public class AlbumsAdapter extends RecyclerView.Adapter<AlbumsAdapter.MyViewHolder> {

private Context mContext;
private List<Album> albumList;
public CardView cardView;
public View itemView;
public ClipData.Item currentItem;
String folder_main = "hismart/hinhmon";
File fileloc = new File(Environment.getExternalStorageDirectory(), folder_main);
String IDCH = "1";
 SwipeRefreshLayout swipeContainer;

public class MyViewHolder extends RecyclerView.ViewHolder {
    public TextView title, count;
    public ImageView thumbnail, overflow;


    public MyViewHolder(View view) {
        super(view);
        title = (TextView) view.findViewById(R.id.title);
        count = (TextView) view.findViewById(R.id.count);
        thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
        overflow = (ImageView) view.findViewById(R.id.overflow);
        swipeContainer = (SwipeRefreshLayout) view.findViewById(R.id.swipeRefreshLayout);
    }
}


public AlbumsAdapter(Context mContext, List<Album> albumList) {
    this.mContext = mContext;
    this.albumList = albumList;
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.album_card, parent, false);

    return new MyViewHolder(itemView);
}

@Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
    Db db = new Db(mContext);



        Album album = albumList.get(position);
        holder.title.setText(album.getName());
        holder.count.setText(album.getGia() + " vnđ");
        Glide.with(mContext).load(album.getUrl()).into(holder.thumbnail);
}

getset 信息

public class Album {
private String id_table;
private String id;
private String name;
private String gia;
private String thumbnail;
private String url;


public Album() {
}

public Album(String id_table, String id, String name, String gias, String thumbnail, String url) {

    this.id_table = id_table;
    this.id = id;
    this.name = name;
    this.gia = gias;
    this.thumbnail = thumbnail;
    this.url = url;


}

public String getId_table() {
    return id_table;
}

public void setId_table(String id_table) {
    this.id_table = id_table;
}

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getGia() {
    return gia;
}

public void setGia(String gia) {
    this.gia = gia;
}

public String getThumbnail() {
    return thumbnail;
}

public void setThumbnail(String thumbnail) {
    this.thumbnail = thumbnail;
}


public String getUrl() {
    return url;
}

public void setUrl(String url) {
    this.url = url;
}


}

数据库

public class Db extends SQLiteOpenHelper {
public Db(Context context) {
    super(context, "Db.sqlite", null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
}

public Cursor getdata(String sql) {
    SQLiteDatabase db = getWritableDatabase();
    Cursor c = db.rawQuery(sql, null);
    return c;
}

public void querydata(String sql) {
    SQLiteDatabase db = getWritableDatabase();
    db.execSQL(sql);
}

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}

您的数据异步来自服务器。所以在 onCreate() 中,第一次应用程序 运行 你的数据还没有从服务器传来,所以当 requestQueue.add(stringRequest) 下的代码执行时,它在你的 sqlite 数据库中也是空的。

要添加来自服务器的新数据,在 public void onResponse(String response) 循环遍历来自服务器的新项目,解析并添加它

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();
}