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