Wednesday, 15 April 2015

Android: Async Thread Issue -



Android: Async Thread Issue -

i have app loading info text files , storing info each file separate arraylist. told load info on async thread though app not crash loading oncreate method (it takes approx 12 seconds load of info text files arraylists).

i have attempted set async thread, have run issue. brand new async threads, not know/yet understand of details (i trying piece info different sources). here relevent code:

@override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_name); new loaddata().execute(); arraylistelement = arraylist1.get(0); } private class loaddata extends asynctask<void, void, void> { progressdialog dialog; protected void onpreexecute() { dialog = new progressdialog(classname.this); dialog.setprogressstyle(progressdialog.style_spinner); dialog.show(); } @override protected void doinbackground(void... arg0) { // todo auto-generated method stub populatearraylists(); homecoming null; } /*protected void onprogressupdate() { } protected void onpostexecute() { }*/ }

i getting indexoutofboundsexception (invalid index 0, size 0) @ lastly statement in oncreate method.

all want load info on separate thread because though app not crash, told should it. ui thread should handle of rest. app working fine until added async thread code.

how files read can seen here: android: asynch thread needed?

what doing wrong?

you returning null doinbackground, of course of study fails. utilize asynctask it's meant do. work correctly, need correctly define asynctask appropriate type paramaters.

instead of making populatearraylists have side effects of updating other field, have method like:

void list<foo> getlistoffoo() { arraylist<foo> listoffoos = getthelistsomehow(); homecoming listoffoos; }

for example:

public class myactivity extends activity { public void dosomething(list<string> stringlist) { //do here } class myasynctask extends asynctask<void, void, list<string>> { @override protected list<string> doinbackground(void... params) { arraylist<string> listofstrings = getlistofstrings(); homecoming listofstrings; } @override protected void onpostexecute(list<string> strings) { super.onpostexecute(strings); dosomething(strings); } private list<string> getlistofstrings() { arraylist<string> stringlist = new arraylist<string>(); //this you'd perform expensive operation bufferedreader br = null; seek { br = new bufferedreader(new inputstreamreader(getassets().open( "text1.txt"))); string text; while ((word = br.readline()) != null) { stringlist.add(text); } } grab (ioexception e) { e.printstacktrace(); } { seek { br.close(); // stop reading } grab (ioexception ex) { ex.printstacktrace(); } } homecoming stringlist; } } }

android android-asynctask android-activity

No comments:

Post a Comment