从Android应用程序服务器读取文本文件 [英] Read text file from server in Android app

查看:530
本文介绍了从Android应用程序服务器读取文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception\">android.os.NetworkOnMainThreadException

我想开在一个TextView服务器的文本文件(几句一行),但我目前的code崩溃的应用程序,当我打开活动。我试过:

I want to open a text file (one line with a few words) from a server in a TextView, but my current code crashes the app when I open the activity. I've tried:

urlTextOut = (TextView) findViewById(R.id.URLtextView); 
StringBuilder text = new StringBuilder();

try {
    String str = "";
    URL url = new URL("http://mysite.com/text1.txt");

    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

    while ((str = in.readLine()) != null) {
         text.append(str);
    }
    in.close();
} catch (MalformedURLException e1) {
} catch (IOException e) {
}

urlTextOut.setText(text);

我也试了非常类似于这样:如何读取从网页Android的文本文件?(添加了尝试/捕获它想让他们),但也应声应用。我试着看Apache的HttpComponents但无法弄清楚什么我的意思是用下载的zip文件的事情。

I've also tried something very similar to this: How to read text file in android from web? (with added try/catches where it wanted them) but that also crashed the app. I've tried looking at Apache's HttpComponents but couldn't figure out what I was meant to do with the downloaded zip file.

推荐答案

你可能得到一个的 NetworkOnMainThreadException 。 Android将不会允许你(在你的活动,即直接)使主/ UI线程网络调用。你应该使用一个单独的线程,看到这个问题的一个例子

You're probably getting a NetworkOnMainThreadException. Android will not allow you to make network calls on the main/UI thread (ie directly in your Activity). You should use a separate thread, see this question for an example.

这篇关于从Android应用程序服务器读取文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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