java - Accessing a TextView from AsyncTask (within a fragment) -
firstly, i'm new android programming, sorry if seems silly question, i'm still trying ot head around all! trying update textview in fragment within onpostexecute() asynctask. i'm struggling on how textview layout , update it. seem able create textview on fly , update it, wanted textview i've created in xml layout. have seen loads of similar questions here, none using fragments (its fragment bit i'm trying learn).
you can see code below, tried @ first create textview (tv) in code (commented out) , worked fine. tried textview layout ((textview)rootview.findviewbyid(r.id.tv2)), because cannot declare public string, don't have access in onpostexecute().
am doing silly here??
public static class placeholderfragment extends fragment { string str; //public textview tv; public placeholderfragment() { } @override public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { view rootview = inflater.inflate(r.layout.fragment_tug_boat_main, container, false); tv = (textview)rootview.findviewbyid(r.id.tv2); //tv = new textview(container.getcontext()); tv.settext("hi there"); readextportfolio rext = new readextportfolio(); rext.execute(); return tv; //return rootview; } class readextportfolio extends asynctask<void, void, void> { @override protected void onpreexecute() { tv.settext("fetching data, please wait: "); } @override protected void doinbackground(void... arg0) { try { url url = new url("http://mywebsite.com/andy.txt"); bufferedreader in = new bufferedreader(new inputstreamreader(url.openstream())); str = in.readline(); in.close(); } catch (ioexception e) { str = "error"; } return null; } // executed on ui thread after // time taking process completed @override protected void onpostexecute(void result) { super.onpostexecute(result); tv.settext("completed task, , result : " + str); } } }
xml file (fragment_tug_boat_main) contains...
<textview android:id="@+id/tv2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world2" />
also, i've used stackoverflow years , people answer have saved me hours , hours of work on years. reading , answers.
edit: sorry, should have said. if uncomment "public textview tv;" runtime error: specified child has parent. must call removeview() on childs parent first. didn't think calling removeview() sounded right removeview not exist on textview
all have uncomment //public textview tv; , able use in onpostexecute method.
Comments
Post a Comment