how do i load remote text from a text file into android textview?

半城伤御伤魂 提交于 2020-01-01 18:18:35

问题


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

This is my current code:

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

回答1:


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

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




回答2:


A follow up on the answer, it worked after adding

        if (android.os.Build.VERSION.SDK_INT > 9) {
       StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
       StrictMode.setThreadPolicy(policy);
      }


来源:https://stackoverflow.com/questions/6902560/how-do-i-load-remote-text-from-a-text-file-into-android-textview

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