简体   繁体   English

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

[英]get JSON data from web and display using RecyclerView

I'm new android, I was create app, it get json data from table in phpmyadmin then save in database of app. 我是新来的android,我正在创建应用程序,它从phpmyadmin表中获取json数据,然后保存在应用程序数据库中。 And I read data and display on RecyclerView but when I run app at first time, table database show nothing. 我读取数据并在RecyclerView上显示,但是当我第一次运行应用程序时,表数据库什么也没显示。 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);

Check database name: tbl_mon_app to read database added above: 检查数据库名称: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();

                }
            }

Add data to arraylist and set notify data set changed 将数据添加到arraylist并设置通知数据集已更改

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

}

Here is Recycleview Adapter 这是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 infomation 获取信息

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


}

Database 数据库

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) {
}
}

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. 因此,在onCreate()内部,应用程序首次运行时,您的数据还不是来自服务器,因此,当执行requestQueue.add(stringRequest)下的代码时,sqlite数据库中的数据也为空。

To add new-fresh data from server, inside public void onResponse(String response) loop through new item from server, parse and add it 要从服务器添加新数据,请在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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用AsyncTaskLoader在recyclerview中显示JSON中的数据 - Display data from JSON in recyclerview using AsyncTaskLoader 如何在 android 中使用 recyclerview 显示来自 web 服务器的 JSON 格式数据 - How to display JSON format data from web server using recyclerview in android 如何在android中使用OkHttp从web api获取json数据到RecyclerView - How to get json data to RecyclerView from web api using OkHttp in android 使用 AsyncTask 在 Fragment 的 RecyclerView 中显示来自 json 的数据? - Display data from json in RecyclerView of Fragment using AsyncTask? 在recyclerview中显示从Json和Gson解析的数据 - Display data parsed from Json with Gson in a recyclerview 在recyclerView中获取json数据 - Get json data in recyclerView 如何在Recyclerview中显示json数据? - How to display json data in Recyclerview? 如何从 android 中的 json 中获取数据并在 RecyclerView 中显示? - How to fetch data from json in android and display in RecyclerView? 视频未使用 Toro 视频库从 Web url 显示在 Recyclerview 中 - video not display in Recyclerview from web url using Toro video library 如何从数组列表中获取数据并在 Recyclerview Adapter 中显示该数据? - How to get the data from an arraylist and display that data in Recyclerview Adapter?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM