如何将文本文件中的远程文本加载到android textview中? [英] how do i load remote text from a text file into android textview?

查看:63
本文介绍了如何将文本文件中的远程文本加载到android textview中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经遍历了所有示例,但似乎无法使它正常工作.

I have gone through all the examples and I can not seem to get this to work.

这是我当前的代码:

package hello.android;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class HelloAndroidActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        TextView tv = (TextView) findViewById(R.id.textView1);
        try {
            // Create a URL for the desired page
            URL url = new URL("http://xlradioaustin.com/song/CurrentSong.txt");

            // Read all the text returned by the server
            BufferedReader in = new BufferedReader(new     InputStreamReader(url.openStream()));
            String str;
            while ((str = in.readLine()) != null) {
                // str is one line of text; readLine() strips the newline character(s)
            }
            in.close();
            tv.setText(str);
        } catch (MalformedURLException e) {
            tv.setText("mal");
        } catch (IOException e) {
            tv.setText("io");
        }
    }
}

推荐答案

假设您的Android设备处于在线状态,并且您已为您的应用授予INTERNET权限,请尝试以下操作:

Assuming your Android device is online and you've granted your app the INTERNET permission, try this:

try {
            // Create a URL for the desired page
            URL url = new URL("http://xlradioaustin.com/song/CurrentSong.txt");

            // Read all the text returned by the server
            BufferedReader in = new BufferedReader(new     InputStreamReader(url.openStream()));
            String str;
            StringBuilder sb = new StringBuilder(100);
            while ((str = in.readLine()) != null) {
                sb.append(str);
                // str is one line of text; readLine() strips the newline character(s)
            }
            in.close();
            tv.setText(sb.toString());
        } catch (MalformedURLException e) {
            tv.setText("mal");
        } catch (IOException e) {
            tv.setText("io");
        }

让我知道是否可行:您当前正在循环播放,直到 str 为空,然后再使用该空值.

Let me know if that works: you are currently looping until str is null, then using that null value.

这篇关于如何将文本文件中的远程文本加载到android textview中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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