2011-08-01 8 views
2

私はすべての例を見てきましたが、これはうまくいかないようです。テキストファイルのリモートテキストをAndroidのテキストビューに読み込むにはどうすればよいですか?

これは私の現在のコードです:

あなたのAndroidデバイスがオンラインであり、あなたがINTERNET権限にアプリを許可している、これを試してみてくださいと仮定
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

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

Aが答えにフォローアップ、それは

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

あなたは人生を救う! –

関連する問題