android app crashes when trying to get txt file from webserver

ⅰ亾dé卋堺 提交于 2019-12-11 07:54:48

问题


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:

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:


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.



来源:https://stackoverflow.com/questions/12521456/android-app-crashes-when-trying-to-get-txt-file-from-webserver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!