how to read text file from internet in Android -
i want read remote text file , show content in textview. have written code, doesn't information text file , has "force stop" error. how can find reason of problem or solve it? isn't there wrong in code?
private class downloadfile extends asynctask<string, integer, void> { protected void doinbackground() { try { url url = new url("http://host/f.txt"); bufferedreader in = new bufferedreader(new inputstreamreader(url.openstream())); string line = null; while ((line = in.readline()) != null) { //get lines } in.close(); lbl.settext(line); } catch (malformedurlexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } } protected void onprogressupdate() { //called when background task makes progress } protected void onpreexecute() { //called before doinbackground() started } protected void onpostexecute() { //called after doinbackground() has finished } @override protected void doinbackground(string... arg0) { // todo auto-generated method stub return null; } }
and oncreate code:
downloadfile d=new downloadfile(); d.doinbackground();
please solve problem!
a couple things:
1) cannot modify ui thread background thread. doinbackground()
runs on background thread, should update ui on onpostexecute()
.
2) have 2 implementations of doinbackground()
. first 1 doesn't override doinbackground()
in asynctask. move code 1 overrides asynctask
3) doinbackground()
should return string can use update text on textview in onpostexecute. asynctask should asynctask<string,void,string>
4) when create donwloadfile()
instance should invoke execute(), otherwise background thread not start , doinbackground()
not called.
5) while loop checking if there still data on inputstream, not storing anywhere. use stringbuilder
append incoming information here.
Comments
Post a Comment