【问题标题】:android app crashes when trying to get txt file from webserverandroid 应用程序在尝试从网络服务器获取 txt 文件时崩溃
【发布时间】:2012-09-22 00:20:14
【问题描述】:

我的应用程序在尝试获取远程 txt 文件时崩溃。 即使只是尝试解析一个 url 它也会崩溃。 已设置互联网权限,并且设备/虚拟机已连接到互联网。

LogCat:

代码sn-p:

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

我不明白我做错了什么。提前感谢您的帮助。

//编辑:添加log cat sn -p

【问题讨论】:

  • 任何时候发生崩溃,重要的信息都会记录在LogCat中。请发布您的相关 logcat 异常。
  • 添加了日志猫截图的链接
  • @user1687295 您是在哪个设备 API 版本上测试此应用程序?
  • 它在 api 级别 10 (android 2.3.3) 上运行

标签: android text-files


【解决方案1】:

由于主 UI 线程上的大量网络活动导致应用程序崩溃,这本身并不是一个很好的做法,因为应用程序可能会停止响应并可能被操作系统杀死。您应该始终尝试在某个单独的线程中进行后台处理,而不是在主 UI 线程中。

将获取文件的代码放在AsyncTaskdoInBackground() 中。

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

您可以通过new DownloadFile().execute("");调用此任务来获取文件,无论您想从哪里获取文件。

【讨论】:

  • 这不仅仅是一种不好的做法——在最新版本的 Android (4+) 下,它被明确禁止。事实上,明显的异常NetworkOnMainThreadException 是 OP 所面临的。 Android 不区分重度和轻量网络使用量。仅仅尝试调用某些方法(例如通过 HTTP URL 调用 openStream())就会给您一个例外。
  • @SevaAlekseyev:哦,好吧。谢谢先生指出。我在 Android 4+ 上工作不多,因此没有意识到这些问题。再次感谢! :)
  • 如果我尝试初始化对象,应用程序不会再崩溃,谢谢,我明天会尝试访问下载文件类传递的文本。
  • 似乎我不知道如何访问文本,我尝试使用静态数组,我在执行 .execute("") 方法后获取它,但它似乎是空的。我可以得到一些帮助吗?
  • 不要将访问文本的代码放在.execute()之后。它将是空的,因为您甚至在 AsyncTask 完成下载之前就调用了它。所以,你需要编写相应的代码来获取onPostExecute()里面的文字。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-07
  • 2018-09-03
  • 2014-04-06
相关资源
最近更新 更多