android - Populate ListView with Runnable - Returns Too Many -
i'm putting app has listview in relativelayout couple linearlayouts inside of it. have adapter, , function items list. function called in oncreate function of apps main process , called in runnable on thread. can see reason why thing might calling adding array many times? (the loop gets called thousands of times when i've added 1 thing array. in oncreate method main process:
array = new arraylist<item>(); //the misbehaving array listview lv = (listview)findviewbyid(r.id.itemlist); this.m_adapter = new itemadapter(this, r.layout.itemlist_item, array); lv.setadapter(this.m_adapter); viewitems = new runnable(){ @override public void run() { getitems(); } }; thread thread = new thread(null, viewitems, "listthread"); thread.start();
the getitems function , second runnable:
private void getitems(){ try{ //try stuff } catch (exception e) { log.e("background_proc", e.getmessage()); } runonuithread(returnres); } private runnable returnres = new runnable() { @override public void run() { if(array != null && array.size() > 0){ listadapter.notifydatasetchanged(); //this loop i'm seeing problem for(int i=0;i<array.size();i++) { listadapter.add(array.get(i)); } } } };
and list adapter:
public class itemadapter extends arrayadapter<item> { public arraylist<item> items; public itemadapter(context context, int textviewresourceid, arraylist<item> items) { super(context, textviewresourceid, items); this.items = items; } @override public view getview(int position, view conview, viewgroup parent) { view v = conview; //the content view if (v == null){ layoutinflater vi = (layoutinflater)getcontext().getsystemservice(context.layout_inflater_service); v = vi.inflate(r.layout.itemlist_item, null); } item o = items.get(position); if (o != null){ textview name = (textview)v.findviewbyid(r.id.item_name); if(name != null){ name.settext("name:"+o.getitemname()); } } return v; } }
any appreciated. thanks, -chris
the problem listview
, other such ui widgets work adapter not allow contents of adapter change unexpectedly on them. need tell listview
change make before next tries interact adapter. if allow thread modify adapter, or modify on main thread don't tell listview
change before allowing else happen, randomly (due races) exceptions thrown listview
adapter changing unexpectedly.
instead, should work (from hackbod's post here):
public class myadapter extends baseadapter<item> { private arraylist<item> mitems; public int getcount() { return mitems != null ? mitems.size() : 0; } public myitem getitem(int position) { return mitems.get(i); } /* ... */ }
and populate listview
with,
private handler mhandler = new handler(); private void setdatafromthread(arraylist<item> data) { // enqueue work on mhandler change data on // main thread. mhandler.post(new runnable() { @override public void run() { mitems = newdata; notifydatasetchanged(); } }); }
Comments
Post a Comment