2011-08-01 111 views
2

我已经通过所有的例子,我似乎无法得到这个工作。如何将文本文件中的远程文本加载到android textview中?

这是我当前的代码:

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

你可以发表你的堆栈跟踪后工作?不知道确切的错误是什么,很难提供解决方案。 –

回答

3

假设你的Android设备在线,你已经授予您的应用INTERNET权限,试试这个:

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为空,然后使用该空值。

+0

是的,如果你是新的权限,看看这个示例清单:http://developer.android.com/resources/samples/SampleSyncAdapter/AndroidManifest.html – Noah

+0

好吧,我走了一个不同的位,它似乎工作之后我添加了权限, 但我怎么能让它循环,并刷新文本文件每15-20秒?这是一个在线广播电台,我们有一个文本文件,通常会随着当前播放轨迹更新 – drooh

+0

您需要确保您在正确的线程上运行,否则它是非常标准的:将它打包成方法并用定时器触发它。 – Femi

1

一个跟进的答案,将其添加

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

你救了我的命! –

相关问题