java - Strange behavior of custom listview with sqlite -
i trying create shopping cart app , going great stuck last 3 day did search lot in stackoverflow not answer.i populating listview server , there 2 buttons in each row plus(for adding quantity) , minus (decrements it). screen adding quantity cart. trying insert row sqlite database upon clicking either of 2 buttons , have achieved , show these data in next activity inside listview. here problem starts when insert data shows during updation showing strange behavior. if click on first 3 rows insertion , updation working fine if scroll down , click on item instead of updating each time inserting.. know question quite big , lengthy not find way summarize sorry.. please me ..
here listview class.
public class myfragment extends fragment implements view.onclicklistener{ int mcurrentpage; private listview listview; recyclerview recyclerview; private feedlistadapter listadapter; private list<feeditem> feeditems; private progressdialog pdialog; private list<feeditem> productsincart = new arraylist<feeditem>(); private relativelayout content; private sharedpreferences preference; textview badge,prices; int totalcount=0,newcount = 0; int lastcount; int totalprice; sqlitedatabase database; public static final string total_count = "count"; dbhelper mhelper; boolean isupdate; string userid,price,pname,position; private button checkout; @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); /** getting arguments bundle object */ bundle data = getarguments(); /** getting integer data of key current_page bundle */ mcurrentpage = data.getint("current_page", 0); } @override public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { view v = inflater.inflate(r.layout.myfragment_layout, container, false); recyclerview= (recyclerview) v.findviewbyid(r.id.my_recycler_view); content = (relativelayout)v.findviewbyid(r.id.content); badge = (textview)v.findviewbyid(r.id.all_comments); checkout = (button)v.findviewbyid(r.id.checkout); prices = (textview)v.findviewbyid(r.id.price); feeditems = new arraylist<feeditem>(); new jsonasynctask() .execute("http://api.androidhive.info/feed/feed.json"); listadapter = new feedlistadapter(getactivity(), feeditems); recyclerview.setadapter(listadapter); recyclerview.sethasfixedsize(true); recyclerview.setlayoutmanager(new linearlayoutmanager(getactivity())); pdialog = new progressdialog(getactivity()); pdialog.setmessage("please wait..."); pdialog.setcancelable(true); listadapter.setonaddnum(this); listadapter.setonsubnum(this); mhelper=new dbhelper(getactivity()); content.setonclicklistener(new view.onclicklistener() { @override public void onclick(view arg0) { // todo auto-generated method stub intent = new intent(getactivity(),checkoutfooter.class); startactivity(i); getactivity().overridependingtransition (r.anim.slide_in_bottom, r.anim.slide_out_bottom); } }); checkout.setonclicklistener(new view.onclicklistener() { @override public void onclick(view arg0) { // todo auto-generated method stub if (userid != null){ intent = new intent(getactivity(),checkout.class); startactivity(i); } else{ toast.maketext(getactivity(), "cart empty! please add few products cart.", toast.length_short).show(); } } }); return v; } // todo auto-generated method stub class jsonasynctask extends asynctask<string, void, boolean> { @override protected void onpreexecute() { super.onpreexecute(); } @override protected boolean doinbackground(string... urls) { try { //------------------>> httpget httppost = new httpget(urls[0]); httpclient httpclient = new defaulthttpclient(); httpresponse response = httpclient.execute(httppost); // statusline stat = response.getstatusline(); int status = response.getstatusline().getstatuscode(); if (status == 200) { httpentity entity = response.getentity(); string data = entityutils.tostring(entity); jsonobject jsono = new jsonobject(data); jsonarray jarray = jsono.getjsonarray("feed"); (int = 0; < jarray.length(); i++) { jsonobject feedobj = jarray.getjsonobject(i); // actors actor = new actors(); feeditem item = new feeditem(); item.setobservation(feedobj.optstring("name")); item.setsummary(feedobj.optstring("timestamp")); item.setname(feedobj.optstring("name")); feeditems.add(item); } return true; } //------------------>> } catch (parseexception e1) { e1.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } catch (jsonexception e) { e.printstacktrace(); } return false; } protected void onpostexecute(boolean result) { if(result == false){ toast.maketext(getactivity(), "unable fetch data server", toast.length_long).show(); } else{ listadapter.notifydatasetchanged(); } pdialog.dismiss(); } } @override public void onclick(view view) { object tag = (integer) view.gettag(); switch (view.getid()){ case r.id.btnaddtocart1: // feeditem item = feeditems.get(tag); if (tag != null && tag instanceof integer) { int position = (integer) tag; int num =feeditems.get(position).getnum(); int price =feeditems.get(position).getprice(); string pname = feeditems.get(position).getname(); string product_name = feeditems.get(position).getname(); num++; feeditems.get(position).setnum(num); feeditems.get(position).setprice(position); toast.maketext(getactivity(), product_name+ " added cart!", toast.length_short).show(); preference = getactivity().getsharedpreferences("state", context.mode_private); preference.edit().putstring("quantity", string.valueof(num)).apply(); preference.edit().putstring("price", string.valueof(num*position)).apply(); preference.edit().putstring("pname",product_name).apply(); preference.edit().putstring("position",string.valueof(position)).apply(); updatedata(); listadapter.notifydatasetchanged(); } break; case r.id.btnaddtocart5: if (tag != null && tag instanceof integer) { int position = (integer) tag; int num =feeditems.get(position).getnum(); int price =feeditems.get(position).getprice(); if (num>0) { num--; feeditems.get(position).setnum(num); feeditems.get(position).setprice(position); preference = getactivity().getsharedpreferences("state", context.mode_private); preference.edit().putstring("quantity", string.valueof(num)).apply(); preference.edit().putstring("price", string.valueof(num*position)).apply(); preference.edit().putstring("position",string.valueof(position)).apply(); updatedata(); listadapter.notifydatasetchanged(); } else{ num= 0; database.delete( dbhelper.table_name, dbhelper.key_id + "=" + (position+1), null); listadapter.notifydatasetchanged(); } } break; } } public void onresume(){ super.onresume(); } private void updatedata() { preference = getactivity().getsharedpreferences("state", context.mode_private); userid = preference.getstring("quantity", null); price = preference.getstring("price", null); pname = preference.getstring("pname", null); position = preference.getstring("position", null); int counts = integer.parseint(position); if(userid == null){ badge.settext("0"); } else{ checkout.setenabled(true); badge.settext(string.valueof(userid)); database = mhelper.getreadabledatabase(); /*cursor curs = database.rawquery("select sum(price) cart", null); if(curs.movetofirst()) { int total = curs.getint(0); system.out.println("total sum of price : "+total); prices.settext(string.valueof(total)+" rs/-"); } */ cursor cur = null; string query = "select * " + dbhelper.table_name + " " +dbhelper.key_id+"=?;" ; cur = database.rawquery(query,new string[] {string.valueof(counts+1)}); if((cur != null) && (cur.getcount() > 0)){ database = mhelper.getwritabledatabase(); contentvalues cv = new contentvalues(); cv.put(dbhelper.key_count,userid); cv.put(dbhelper.key_price, price); cv.put(dbhelper.key_pname, pname); system.out.println("database values : "+cv); database.update(dbhelper.table_name, cv, dbhelper.key_id+" = '" + string.valueof(counts+1) + "'", null); cur.close(); } else{ database = mhelper.getwritabledatabase(); contentvalues cv = new contentvalues(); cv.put(dbhelper.key_count,userid); cv.put(dbhelper.key_price, price); cv.put(dbhelper.key_pname, pname); system.out.println("database values : "+cv); database.insert(dbhelper.table_name, null, cv); cur.close(); } } } }
my checkout page showing data sqlite.
public class checkout extends appcompatactivity{ private arraylist<string> userid = new arraylist<string>(); private arraylist<string> product_name = new arraylist<string>(); private arraylist<string> product_quantity = new arraylist<string>(); private arraylist<string> product_price = new arraylist<string>(); private arraylist<integer> quantitylist = new arraylist<integer>(); private arraylist<integer> amountlist = new arraylist<integer>(); listview recyclerview; textview quantity; textview amount; button pay; dbhelper mhelper; sqlitedatabase database; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.checkout); recyclerview= (listview) findviewbyid(r.id.my_recycler_view); amount = (textview) findviewbyid(r.id.amount); quantity = (textview) findviewbyid(r.id.quantity); pay = (button) findviewbyid(r.id.pay); mhelper = new dbhelper(this); } @override protected void onresume() { displaydata(); super.onresume(); } private void displaydata() { database = mhelper.getwritabledatabase(); cursor mcursor = database.rawquery("select * " + dbhelper.table_name, null); int sum = 0; int qty = 0; userid.clear(); product_name.clear(); product_quantity.clear(); quantitylist.clear(); amountlist.clear(); product_price.clear(); if (mcursor.movetofirst()) { { userid.add(mcursor.getstring(mcursor.getcolumnindex(dbhelper.key_id))); product_name.add(mcursor.getstring(mcursor.getcolumnindex(dbhelper.key_pname))); product_quantity.add(mcursor.getstring(mcursor.getcolumnindex(dbhelper.key_count))); product_price.add(mcursor.getstring(mcursor.getcolumnindex(dbhelper.key_price))); } while (mcursor.movetonext()); } displayadapter disadpt = new displayadapter(checkout.this,userid, product_name, product_price,product_quantity); recyclerview.setadapter(disadpt); mcursor.close(); quantitylist = convertinteger(product_quantity); amountlist = converamountinteger(product_price); (int : quantitylist){ qty = qty+i; } (int s : amountlist){ sum = sum +s; } amount.settext(string.valueof(sum)); quantity.settext(string.valueof(qty)); disadpt.notifydatasetchanged(); } private arraylist<integer> converamountinteger( arraylist<string> product_price2) { // todo auto-generated method stub arraylist<integer> result = new arraylist<integer>(); for(string amount : product_price2) { try { //convert string integer, , store integer array list. result.add(integer.parseint(amount)); } catch(numberformatexception nfe) { //system.out.println("could not parse " + nfe); log.w("numberformat", "parsing failed! " + amount + " can not integer"); } } return result; } private arraylist<integer> convertinteger( arraylist<string> product_quantity2) { // todo auto-generated method stub arraylist<integer> result = new arraylist<integer>(); for(string quantity : product_quantity2) { try { //convert string integer, , store integer array list. result.add(integer.parseint(quantity)); } catch(numberformatexception nfe) { //system.out.println("could not parse " + nfe); log.w("numberformat", "parsing failed! " + quantity + " can not integer"); } } return result; }
database class:
public class dbhelper extends sqliteopenhelper { public static string database_name="user.db"; public static final string table_name="cart"; public static final string key_count="cartitem"; public static final string key_pname="product_name"; public static final string key_id="id"; public static final string key_price="price"; public static final string key_created_at="created_at"; public dbhelper(context context) { super(context, database_name, null, 1); } @override public void oncreate(sqlitedatabase db) { string create_table="create table "+table_name+" ("+key_id+" integer primary key, "+key_count+" integer," +key_pname+" text,"+key_price+" integer,"+ key_created_at + " datetime" + ")"; db.execsql(create_table); } @override public void onupgrade(sqlitedatabase db, int oldversion, int newversion) { db.execsql("drop table if exists "+table_name); oncreate(db); }
update : there little mistake changed column name instead of created unique key , working fine..
Comments
Post a Comment