0

I want to read a remote text file and show its content in a textview. I have written this code, but it doesn't get any information from the text file and has "force stop" error. How can I find the reason of this problem or solve it? isn't there anything wrong in my 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 the background task makes any progress
}
protected void onPreExecute() {
     //called before doInBackground() is started
}
protected void onPostExecute() {
     //called after doInBackground() has finished 
}
@Override
protected Void doInBackground(String... arg0) {
    // TODO Auto-generated method stub
    return null;
}
}

and my onCreate code:

DownloadFile d=new DownloadFile();
d.doInBackground();

please solve my problem!

elia
  • 83
  • 1
  • 1
  • 5

2 Answers2

0

A couple things:

1) You cannot modify the UI thread from a background Thread. doInBackground() runs on a background Thread, you should update your UI on onPostExecute().

2) You have two implementations of doInBackground(). The first one doesn't override the doInBackground() in AsyncTask. Move this code to the one that overrides AsyncTask

3) doInBackground() should return a String so you can use it to update the text on your TextView in onPostExecute. AsyncTask should look like this AsyncTask<String,Void,String>

4) When you create the DonwloadFile() instance you should invoke its execute(), otherwise the background Thread will not start and doInBackground() will not get called.

5) Your while loop is only checking if there is still data on the InputStream, but it is not storing it anywhere. Use a StringBuilder to append incoming information like here.

Community
  • 1
  • 1
Emmanuel
  • 13,083
  • 4
  • 39
  • 53
0

It is easier for people to help you if you post the exception stack trace from Logcat.

If you are using Eclipse and don't know what I am talking about, look here

Community
  • 1
  • 1
AHaahr
  • 409
  • 1
  • 4
  • 16