开发者

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

开发者 https://www.devze.com 2023-03-24 03:47 出处:网络
I have gone through all the examples and I can not seem to get this to work. This is my current code:

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 开发者_Python百科character(s)
            }
            in.close();
            tv.setText(str);
        } catch (MalformedURLException e) {
            tv.setText("mal");
        } catch (IOException e) {
            tv.setText("io");
        }
    }
}


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消