当试图从Web服务器txt文件的Andr​​oid应用程序崩溃 [英] android app crashes when trying to get txt file from webserver

查看:122
本文介绍了当试图从Web服务器txt文件的Andr​​oid应用程序崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图让远程txt文件,当我的应用程序崩溃。
哪怕只是尝试分析它崩溃的URL。
网络权限设置和设备/ VM具有连接到互联网。

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中:

LogCat:

code片断:

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();
    }

我不inderstand什么我做错了。感谢您提前帮助。

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

//编辑:添加日志猫段

//edit: added log cat snippet

推荐答案

该应用程序是由于主UI线程,它本身不是一个非常好的做法沉重的网络活动崩溃,因为应用程序可以停止响应,并且可能会由操作系统杀害。你应该总是尝试做你的后台处理一些单独的线程,而不是在主UI线程上。

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.

把你的code将文件提取 doInBackground() 的的 AsyncTask的

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

您可以把这个任务的调用来获取通过 新DownloadFile()执行()的文件。 在任何你你会希望得到的文件。

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.

这篇关于当试图从Web服务器txt文件的Andr​​oid应用程序崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆