android - the List<> being empty after filling it in for loop -
i want details db, , put them in list. - inside loop can see list gets details (list size increases , values in list true. - after loop ends, check list , find size want, fields values null!! list variable defined outside function (i.e it's class field). see: loop start cursors value put value in list check list value : value ok. loop end.
check list value : value null.
here code:
list<bundle> friends = new arraylist<bundle>(); public list<bundle> getallfriends() { sqlitedatabase db = this.getwritabledatabase(); string check="select * friends"; cursor c = null; string name =""; string id =""; string onlinestt =""; string photourl =""; string friendsince =""; bundle det=new bundle(); if(db!=null) c=db.rawquery(check,null); if(c!=null) if(c.isbeforefirst()&&c.getcount()>0) // if there result/s { c.movetofirst(); { name = c.getstring(0); id = c.getstring(1); onlinestt = c.getstring(2); photourl = c.getstring(3); friendsince = c.getstring(4); det.putstring("name",name);// fill bundle det.putstring("id",id); det.putstring("onlinestt",onlinestt); det.putstring("photourl",photourl); det.putstring("friendsince",friendsince); friends.add(det);// put bundle in list log.d("addfriend---","name in list: "+friends.get(friends.size()-1).getstring("name")); // true value log.d("addfriend---","list size="+friends.size()); // size increased // log.d showed me current value det.clear(); // clear bundle } while(c.movetonext()); if(friends.size()<1) { log.d("fun","no friends found!") ; return null;} } else return null; (int x=0;x<friends.size()-1;x++) log.d("addfriend---","name of friend in list: "+friends.get(x).getstring("name")); // null log.d("addfriend---"," list size after loop end "+friends.size()); // true size return friends;
.... logs results:
addfriend---﹕ name of friend in list: john d/addfriend---﹕ list size=1 d/addfriend---﹕ name of friend in list: fadi ---- after loop: d/addfriend---﹕ list size=2 d/addfriend---﹕ name of friend in list: null d/addfriend---﹕ list size after loop end 2
you should not call
det.clear();
but should create new instance (bundle det = new bundle()
) @ every iteration
Comments
Post a Comment