从Web获取JSON数据并使用RecyclerView显示 [英] get JSON data from web and display using RecyclerView

查看:140
本文介绍了从Web获取JSON数据并使用RecyclerView显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新的android,我正在创建应用程序,它从phpmyadmin中的表中获取json数据,然后保存在应用程序的数据库中.我读取数据并在RecyclerView上显示,但是当我第一次运行应用程序时,表数据库什么也没显示.但是从第二次开始,应用程序就可以读取数据并根据需要显示.

I'm new android, I was create app, it get json data from table in phpmyadmin then save in database of app. And I read data and display on RecyclerView but when I run app at first time, table database show nothing. But from the second time app can read data and display as I want.

请任何人在第一时间作为我的第二次来帮助我运行应用程序. 这是我的代码:

Anyone help me to run app in the first time as the second time please. Here is my code:

   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以读取上面添加的数据库:

Check database name: tbl_mon_app to read database added above:

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

                }
            }

将数据添加到arraylist并设置通知数据集已更改

Add data to arraylist and set notify data set changed

    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适配器

Here is Recycleview Adapter

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数据库中也为空.

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

这篇关于从Web获取JSON数据并使用RecyclerView显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆