Android how to integrate an AsyncTask -
hi have app downloads json
feed , starting become leggy know need use asynctask i'm not sure how integrate code know whats best way integrate it.
heres original code far
public class homeactivity extends listactivity { private mergeadapter adapter=null; private arrayadapter<string> arrayadapter=null; private arrayadapter<string> arrayadapter2=null; private lazyadapter arrayadapter3=null; private static final string apikey = "7668hhf74hhd3dhhs"; private static final string apiuser = "androiduser"; private static string chosenleagueid = null; private static string chosenmethod = null; private static string chosenteamid = null; public string fulldata = null; public string newsfeedrequest = null; public string newsfeedurl = null; public string resultsfeedurl = null; public string lastmonth = null; public string hometeam = null; public string awayteam = null; public string homescore = null; public string awayscore = null; public string attendance = null; public string division = null; public string homescorers = null; public string awayscorers = null; public string resultsfeedrequest = null; public string chosenleagueid = "40"; public list<string> newslist = null; public list<string> newslist2 = null; public list<string> newslist3 = null; public list<string> imagelist = null; public jsonobject resultsdict = null; public view resultsview = null; public int newsamount = 0; long unixtimestamp = system.currenttimemillis() / 1000l; //add time stamp url //public string chosenmethod; public class posttask extends asynctask<void, string, boolean> { @override protected boolean doinbackground(void... params) { boolean result = false; checkpreferences(); publishprogress("progress"); return result; } protected void onprogressupdate(string... progress) { stringbuilder str = new stringbuilder(); (int = 1; < progress.length; i++) { str.append(progress[i] + " "); } } } static string buildhmacsignature(string pkey, string pstringtosign) { string lsignature = "none"; try { mac lmac = mac.getinstance("hmacsha256"); secretkeyspec lsecret = new secretkeyspec(pkey.getbytes(), "hmacsha256"); lmac.init(lsecret); byte[] ldigest = lmac.dofinal(pstringtosign.getbytes()); biginteger lhash = new biginteger(1, ldigest); lsignature = lhash.tostring(16); if ((lsignature.length() % 2) != 0) { lsignature = "0" + lsignature; } } catch (nosuchalgorithmexception lex) { throw new runtimeexception("problems calculating hmac", lex); } catch (invalidkeyexception lex) { throw new runtimeexception("problems calculating hmac", lex); } return lsignature; } public void checkpreferences(){ sharedpreferences preferences = getsharedpreferences("prefs", context.mode_private); chosenmethod = preferences.getstring("chosenmethod", chosenmethod); chosenleagueid = preferences.getstring("chosenleagueid", chosenleagueid); chosenteamid = preferences.getstring("chosenteamid", chosenteamid); log.v("lc", "newsurl" + newsfeedurl); log.v("myapp", "chosenmethod home = " + chosenmethod); log.v("myapp", "chosenleagueid home = " + chosenleagueid); log.v("myapp", "chosenteamid home = " + chosenteamid); if (chosenmethod.equals("team")) { setcontentview(r.layout.homeactteam2); newsamount = 5; loaddata(); } else { setcontentview(r.layout.homeact); newsamount = 10; loaddataleague(); } } public void loadresults(){ resultsfeedrequest = "1.0/league-website/" + chosenleagueid + "/results?&team_id=" + chosenteamid + "&limit=31×tamp=" + unixtimestamp; resultsfeedurl = "https://www.website.com/_services/api/" + resultsfeedrequest; string myhash = buildhmacsignature(apikey, resultsfeedurl); httpclient client = new defaulthttpclient(); httppost post = new httppost(resultsfeedurl); list<namevaluepair> pairs = new arraylist<namevaluepair>(); pairs.add(new basicnamevaluepair("requesttoken", myhash)); pairs.add(new basicnamevaluepair("apiuser", apiuser)); try { post.setentity (new urlencodedformentity(pairs)); httpresponse response = client.execute(post); bufferedreader reader = new bufferedreader(new inputstreamreader(response.getentity().getcontent(), "utf-8")); string json = reader.readline(); fulldata = string.valueof(json); log.v("myapp","resultsdata" + fulldata); newslist = new arraylist<string>(); newslist2 = new arraylist<string>(); newslist3 = new arraylist<string>(); imagelist = new arraylist<string>(); jsonobject obj = new jsonobject(json); jsonobject objdata = obj.getjsonobject("data"); jsonarray jarray = objdata.getjsonarray("results"); if(jarray.length() < 1){ loadlastresults(); }else{ log.v("lc", "this month has results"); } // // for(int t = 0; t < newsamount; t++){ // jsonobject newstitledict = jarray.getjsonobject(t); // imagelist.add(newstitledict.getstring("image_small")); // newslist3.add(newstitledict.getstring("title")); // // } // // for(int t = 0; t < 1; t++){ // jsonobject newstitledict = jarray.getjsonobject(t); // // newslist.add(newstitledict.getstring("title")); // newslist2.add(newstitledict.getstring("title")); // // } // } catch (clientprotocolexception e) { // todo auto-generated catch block e.printstacktrace(); } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } catch (jsonexception e) { // todo auto-generated catch block e.printstacktrace(); } } public void loadlastresults(){ resultsfeedrequest = "1.0/league-website/" + chosenleagueid + "/results?month=04&team_id=" + chosenteamid + "&limit=31×tamp=" + unixtimestamp; resultsfeedurl = "https://www.website.com/_services/api/" + resultsfeedrequest; string myhash = buildhmacsignature(apikey, resultsfeedurl); date anothercurdate = new date(); simpledateformat formatter = new simpledateformat("mm"); string curmonth = formatter.format(anothercurdate); int int = integer.parseint(curmonth); int monthint = int -1; curmonth = (string) (string.valueof(monthint)); if (curmonth.equals("1")){ lastmonth = "12"; } else { if(curmonth.length() < 2){ lastmonth = "0" + curmonth; } else { lastmonth = curmonth; } } log.v("lc","month= " + curmonth); log.v("lc","lastmonth= " + lastmonth); httpclient client = new defaulthttpclient(); httppost post = new httppost(resultsfeedurl); list<namevaluepair> pairs = new arraylist<namevaluepair>(); pairs.add(new basicnamevaluepair("requesttoken", myhash)); pairs.add(new basicnamevaluepair("apiuser", apiuser)); try { post.setentity (new urlencodedformentity(pairs)); httpresponse response = client.execute(post); bufferedreader reader = new bufferedreader(new inputstreamreader(response.getentity().getcontent(), "utf-8")); string json = reader.readline(); fulldata = string.valueof(json); log.v("myapp","resultsdata" + fulldata); newslist = new arraylist<string>(); newslist2 = new arraylist<string>(); newslist3 = new arraylist<string>(); imagelist = new arraylist<string>(); jsonobject obj = new jsonobject(json); jsonobject objdata = obj.getjsonobject("data"); jsonarray jarray = objdata.getjsonarray("results"); for(int t = 0; t < 1; t++){ resultsdict = jarray.getjsonobject(t); hometeam = resultsdict.getstring("hometeam"); awayteam = resultsdict.getstring("awayteam"); homescore = resultsdict.getstring("homescore"); awayscore = resultsdict.getstring("awayscore"); attendance = resultsdict.getstring("attendance"); division = resultsdict.getstring("division"); log.v("lc","hometeam" + hometeam); log.v("lc","awayteam" + awayteam); } resultsview = layoutinflater.from(getbasecontext()).inflate(r.layout.resultscell, null); textview hometeam = (textview) resultsview.findviewbyid(r.id.hometeam); hometeam.settext(hometeam); textview awayteam = (textview) resultsview.findviewbyid(r.id.awayteam); awayteam.settext(awayteam); textview homescore = (textview) resultsview.findviewbyid(r.id.homescore); homescore.settext(homescore); textview awayscore = (textview) resultsview.findviewbyid(r.id.awayscore); awayscore.settext(awayscore); textview attendance = (textview) resultsview.findviewbyid(r.id.attendence); attendance.settext("att:" + attendance); textview division = (textview) resultsview.findviewbyid(r.id.division); division.settext(division); log.v("lc", "resultsdict" + resultsdict); } catch (clientprotocolexception e) { // todo auto-generated catch block e.printstacktrace(); } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } catch (jsonexception e) { // todo auto-generated catch block e.printstacktrace(); } } public void loadnews(){ newsfeedrequest = "1.0/league-website/" + chosenleagueid + "/news?timestamp=" + unixtimestamp; newsfeedurl = "https://www.website.com/_services/api/" + newsfeedrequest; string myhash = buildhmacsignature(apikey, newsfeedurl); log.v("lc" , "resultsurl=" + resultsfeedurl); httpclient client = new defaulthttpclient(); httppost post = new httppost(newsfeedurl); list<namevaluepair> pairs = new arraylist<namevaluepair>(); pairs.add(new basicnamevaluepair("requesttoken", myhash)); pairs.add(new basicnamevaluepair("apiuser", apiuser)); try { post.setentity (new urlencodedformentity(pairs)); httpresponse response = client.execute(post); bufferedreader reader = new bufferedreader(new inputstreamreader(response.getentity().getcontent(), "utf-8")); string json = reader.readline(); fulldata = string.valueof(json); log.v("myapp","newsdata" + fulldata); newslist = new arraylist<string>(); newslist2 = new arraylist<string>(); newslist3 = new arraylist<string>(); imagelist = new arraylist<string>(); jsonobject obj = new jsonobject(json); jsonobject objdata = obj.getjsonobject("data"); jsonarray jarray = objdata.getjsonarray("news"); log.v("lc","newsamount= " + newsamount); for(int t = 0; t < newsamount; t++){ jsonobject newstitledict = jarray.getjsonobject(t); imagelist.add(newstitledict.getstring("image_small")); newslist3.add(newstitledict.getstring("title")); } for(int t = 0; t < 1; t++){ jsonobject newstitledict = jarray.getjsonobject(t); newslist.add(newstitledict.getstring("title")); // newslist2.add(newstitledict.getstring("title")); } } catch (clientprotocolexception e) { // todo auto-generated catch block e.printstacktrace(); } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } catch (jsonexception e) { // todo auto-generated catch block e.printstacktrace(); } } public void mergeadaptersetup(){ arrayadapter = new arrayadapter<string>(this, r.layout.single_item, newslist); arrayadapter2 = new arrayadapter<string>(this, r.layout.resultscell, newslist2); //arrayadapter3 = new arrayadapter(this, r.layout.complex_item, newslist3); string[] mstrings = (string[]) imagelist.toarray(new string[imagelist.size()]); string[] news = (string[]) newslist3.toarray(new string[newslist3.size()]); arrayadapter3 = new lazyadapter(this, mstrings, news); listview list = getlistview(); list.settextfilterenabled(true); layoutinflater inflater = (layoutinflater) this.getsystemservice(context.layout_inflater_service ); view header = inflater.inflate( r.layout.homeheader, list, false); view header2 = inflater.inflate( r.layout.homeheader2, list, false); view header3 = inflater.inflate( r.layout.homeheader3, list, false); //setlistadapter (arrayadapter); adapter = new mergeadapter(); adapter.addview(header); adapter.addadapter(arrayadapter); adapter.addview(header2); adapter.addview(resultsview); adapter.addview(header3); adapter.addadapter(arrayadapter3); setlistadapter(adapter); } public void loaddataleague(){ string myhash = buildhmacsignature(apikey, newsfeedurl); httpclient client = new defaulthttpclient(); httppost post = new httppost(newsfeedurl); list<namevaluepair> pairs = new arraylist<namevaluepair>(); pairs.add(new basicnamevaluepair("requesttoken", myhash)); pairs.add(new basicnamevaluepair("apiuser", apiuser)); try { post.setentity (new urlencodedformentity(pairs)); httpresponse response = client.execute(post); bufferedreader reader = new bufferedreader(new inputstreamreader(response.getentity().getcontent(), "utf-8")); string json = reader.readline(); fulldata = string.valueof(json); log.v("myapp","newsdata" + fulldata); newslist = new arraylist<string>(); newslist2 = new arraylist<string>(); newslist3 = new arraylist<string>(); imagelist = new arraylist<string>(); jsonobject obj = new jsonobject(json); jsonobject objdata = obj.getjsonobject("data"); jsonarray jarray = objdata.getjsonarray("news"); log.v("lc","newsamount= " + newsamount); for(int t = 0; t < newsamount; t++){ jsonobject newstitledict = jarray.getjsonobject(t); imagelist.add(newstitledict.getstring("image_small")); newslist3.add(newstitledict.getstring("title")); } for(int t = 0; t < 1; t++){ jsonobject newstitledict = jarray.getjsonobject(t); newslist.add(newstitledict.getstring("title")); newslist2.add(newstitledict.getstring("title")); } } catch (clientprotocolexception e) { // todo auto-generated catch block e.printstacktrace(); } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } catch (jsonexception e) { // todo auto-generated catch block e.printstacktrace(); } arrayadapter = new arrayadapter<string>(this, r.layout.single_item, newslist); arrayadapter2 = new arrayadapter<string>(this, r.layout.single_item, newslist2); //arrayadapter3 = new arrayadapter(this, r.layout.complex_item, newslist3); string[] mstrings = (string[]) imagelist.toarray(new string[imagelist.size()]); string[] news = (string[]) newslist3.toarray(new string[newslist3.size()]); arrayadapter3 = new lazyadapter(this, mstrings, news); listview list = getlistview(); list.settextfilterenabled(true); layoutinflater inflater = (layoutinflater) this.getsystemservice(context.layout_inflater_service ); view header3 = inflater.inflate( r.layout.homeheader3, list, false); //setlistadapter (arrayadapter); adapter = new mergeadapter(); adapter.addview(header3); adapter.addadapter(arrayadapter3); setlistadapter(adapter); } public void loaddata(){ loadresults(); loadnews(); mergeadaptersetup(); } @override protected void oncreate(bundle savedinstancestate) { // todo auto-generated method stub super.oncreate(savedinstancestate); posttask jsontask; jsontask = new posttask(); jsontask.execute(); button backbtn = (button) findviewbyid(r.id.backbtn); //listening button event backbtn.setonclicklistener(new view.onclicklistener() { public void onclick(view arg0) { //starting new intent intent previousscreen = new intent(getapplicationcontext(), chooseteamactivity.class); chosenmethod = "null"; sharedpreferences preferences = getsharedpreferences("prefs", context.mode_private); sharedpreferences.editor editor = preferences.edit(); editor.putstring("chosenmethod", chosenmethod); editor.commit(); previousscreen.putextra("fulldata", fulldata); startactivity(previousscreen); } }); } @override public boolean oncreateoptionsmenu(menu menu) { menuinflater inflater = getmenuinflater(); inflater.inflate(r.menu.menu, menu); return true; } @override public boolean onoptionsitemselected(menuitem item) { if (item.getitemid() == r.id.home) { startactivity(new intent(homeactivity.this, homeactivity.class)); return(true); } if (item.getitemid() == r.id.match) { startactivity(new intent(homeactivity.this, matchactivity.class)); return(true); } if (item.getitemid() == r.id.teams) { startactivity(new intent(homeactivity.this, teamsactivity.class)); return(true); } if (item.getitemid() == r.id.twitter) { startactivity(new intent(homeactivity.this, twitteractivity.class)); return(true); } if (item.getitemid() == r.id.info) { startactivity(new intent(homeactivity.this, infoactivity.class)); return(true); } return(super.onoptionsitemselected(item)); } }
error
java.lang.nullpointerexception 06-07 12:56:34.338: e/androidruntime(2688): @ android.app.activitythread.performlaunchactivity(activitythread.java:1821) 06-07 12:56:34.338: e/androidruntime(2688): @ android.app.activitythread.handlelaunchactivity(activitythread.java:1842) 06-07 12:56:34.338: e/androidruntime(2688): @ android.app.activitythread.access$1500(activitythread.java:132) 06-07 12:56:34.338: e/androidruntime(2688): @ android.app.activitythread$h.handlemessage(activitythread.java:1038) 06-07 12:56:34.338: e/androidruntime(2688): @ android.os.handler.dispatchmessage(handler.java:99) 06-07 12:56:34.338: e/androidruntime(2688): @ android.os.looper.loop(looper.java:143) 06-07 12:56:34.338: e/androidruntime(2688): @ android.app.activitythread.main(activitythread.java:4263) 06-07 12:56:34.338: e/androidruntime(2688): @ java.lang.reflect.method.invokenative(native method) 06-07 12:56:34.338: e/androidruntime(2688): @ java.lang.reflect.method.invoke(method.java:507) 06-07 12:56:34.338: e/androidruntime(2688): @ com.android.internal.os.zygoteinit$methodandargscaller.run(zygoteinit.java:839) 06-07 12:56:34.338: e/androidruntime(2688): @ com.android.internal.os.zygoteinit.main(zygoteinit.java:597) 06-07 12:56:34.338: e/androidruntime(2688): @ dalvik.system.nativestart.main(native method) 06-07 12:56:34.338: e/androidruntime(2688): caused by: java.lang.nullpointerexception 06-07 12:56:34.338: e/androidruntime(2688): @ homeactivity.oncreate(homeactivity.java:637) 06-07 12:56:34.338: e/androidruntime(2688): @ android.app.instrumentation.callactivityoncreate(instrumentation.java:1072) 06-07 12:56:34.338: e/androidruntime(2688): @ android.app.activitythread.performlaunchactivity(activitythread.java:1785)
hers example of async task, should put in async task because in android 3.0 > there rules not...
you need put in async task, not run in main thread in 3.0 >
use this:
public class jsontask extends asynctask<void, string, boolean> { @override protected boolean doinbackground(void... params) { boolean result = false; //all code goes in here //if want on ui use progress update publishprogress("progress"); return result; } protected void onprogressupdate(string... progress) { stringbuilder str = new stringbuilder(); (int = 1; < progress.length; i++) { str.append(progress[i] + " "); } } }
you need reference outside async task
jsontask jsontask;
then need start it
jsontask = new jsontask(); jsontask.execute();
i had exact same problem while ago, goodluck
Comments
Post a Comment