android - AsyncTask behavior confusion -
i have project:
im trying undestand problem , how can solved, point dont know problem. have button , textview. when button clicked procedure called:
android:onclick="pulsaboton"
and textview show me output.
this main_activity.java
package com.example.pruebasonidos; import android.app.activity; import android.os.asynctask; import android.os.bundle; import android.view.view; import android.widget.textview; public class mainactivity extends activity { public string cadena1="", cadena2=""; public textview tv; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); tv = (textview) findviewbyid(r.id.textview01); } public class generamusica extends asynctask<string, integer, integer> { @override protected void onpreexecute(){ tv.settext(tv.gettext().tostring()+"pre execute"); } @override protected integer doinbackground(string...strings) { string cadena=strings[0]; tv.settext(tv.gettext().tostring()+cadena); return null; } @override protected void onpostexecute(integer bytes){ tv.settext(tv.gettext().tostring()+"post execute"); } } public void pulsaboton(view v) { cadena1="123"; cadena2="111"; tv.settext(""); new generamusica().execute(cadena1); new generamusica().execute(cadena2); } @override public boolean oncreateoptionsmenu(menu menu) { // inflate menu; adds items action bar if present. getmenuinflater().inflate(r.menu.main, menu); return true; } }
when pulsaboton clicked, textview1 display this:
preexecutepreexecute123111postexecutepostexecute
i want output:
preexecute123postexecutepreexecute111postexecute
what error????
warning: interface modification executed outside of ui thread!
protected integer doinbackground(string...strings) { ... tv.settext(tv.gettext().tostring()+cadena); ... }
why think asynctask
exposes onpreexecute
, onpostexecute
? couldn't of interface work in doinbackground
, before , after async code?
in android, ui needs accessed main thread, foreground thread; doinbackground
not run in.
if need post updates ui during execution of asynctask
, use publishprogress
mechanism.
edit: "properly" accesing interface lot more complex using onpreexecute
, onpostexecute
. see this blog post. maybe should try loader
api, it's less troublesome.
Comments
Post a Comment