android - Cannot touch a external view from inside a AsyncTask... but not always -
i have made asynctask should compile textview. short recap of did. deleted lot of lines hope didn't forget anything.
public class myclass extends relativelayout { private textview messagetextview; public myclass(context context) { super(context); init(context); } public myclass(context context, attributeset attrs, int defstyle) { super(context, attrs, defstyle); init(context); } public myclass(context context, attributeset attrs) { super(context, attrs); init(context); } private void init(context context) { createlayoutcontent(); run(); } private void createlayoutcontent (context context) { this.setlayoutparams(new relativelayout.layoutparams (relativelayout.layoutparams.match_parent, 0)); messageview = new textview(context); messageview.settext("test"); this.addview(messageview); } private void start() { new asynctask<void, string, void>() { @override protected void doinbackground(void... params) { try { string s_message = "test2"; messageview.settext(s_message); **// here error //** } catch (malformedurlexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } catch (jsonexception e) { e.printstacktrace(); } return null; } }.execute(); } }
after this, put object directly in layout:
<<...>myclass android:id="@+id/test" android:layout_width="match_parent" android:layout_height="wrap_content" />
now problem on some apps works. activity runs, setcontentview() creates ui objects , fine. on other apps, continuously receive error says "only original thread created view hierarchy can touch views."
i error, don't why on apps works fine... more weird, happened me once app on gave error, started working , went error after 2 correct runs!!
this totally weird.
i know maybe details not enough detect error, excuse me this, checked detais think @ , not find notable differences between when works , when not. maybe more expert eyes can detect something, explain or suggest me debug. can 1 me?
thank much.
i'm not sure, why works times. should fail every time. may works, if android system decides run background thread code within ui thread.
here fixes problem: move "touch views" things onpostexcution()
or onprogressupdate()
. ui meant touched within ui thread. asynctask helps quite conveniently. asynctask's
methods doinbackground()
running on ui thread.
so, never change views
directly doinbackground()
.
private void start() { new asynctask<void, string, string>() { @override protected string doinbackground(void... params) { try { string s_message = "test2"; return s_message; } catch (malformedurlexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } catch (jsonexception e) { e.printstacktrace(); } return null; } @override protected void onpostexecute(string s) { messageview.settext(s); } }.execute(); }
Comments
Post a Comment