android app crashes when trying to get txt file fr

2019-08-06 11:23发布

my app crashes when trying to get a remote txt file. even if just try to parse a url it crashes. internet permission is set and the device/vm has connection to the internet.

LogCat: enter image description here

code snippet:

try {
    // the following line is enough to crash the app
    URL url = new URL("http://www.i.am/not/going/to/show/you/this.txt");


    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
    String line = null;
    while ((line = in.readLine()) != null) {
        //get lines
    }
    in.close();


    } catch (MalformedURLException e) {

        e.printStackTrace();
    } catch (IOException e) {

        e.printStackTrace();
    }

i don't inderstand what i'm doing wrong. thanks for help in advance.

//edit: added log cat snippet

1条回答
Luminary・发光体
2楼-- · 2019-08-06 11:44

The application is crashing due to heavy network activity on the main UI thread, which itself is not a very good practice, as the application can stop responding and might get killed by the OS. You should always try to do your background processing in some separate thread, and not on the main UI thread.

Put your code to fetch the file inside the doInBackground() of an AsyncTask.

private class DownloadFile extends AsyncTask<String, Integer, Void> {
     protected void doInBackground() {
         try {

       URL url = new URL("http://www.i.am/not/going/to/show/you/this.txt");       

    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
    String line = null;
    while ((line = in.readLine()) != null) {
        //get lines
    }
    in.close();


    } 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 
 }
  }

You can make a call to this task to fetch the file by new DownloadFile().execute(""); where ever you would you want to get the file.

查看更多
登录 后发表回答