2016-07-14 2 views
-1

テキストファイル(* .txt)をサーバーにアップロードしましたが、今度はテキストファイルを読みたいと思っています...Android - どのようにURLからテキストファイルを読むことができますか?

私は運が無ければこの例を試しました。

アプリケーションが自身を閉じている
ArrayList<String> urls=new ArrayList<String>(); //to read each line 
TextView t; //to show the result 
try { 
     // Create a URL for the desired page 
     URL url = new URL("mydomainname.de/test.txt"); //My text file location 
     // Read all the text returned by the server 
     BufferedReader in = new BufferedReader(new  InputStreamReader(url.openStream())); 

    t=(TextView)findViewById(R.id.TextView1); 
    String str; 
    while ((str = in.readLine()) != null) { 
     urls.add(str); 


    } 
    in.close(); 
    } catch (MalformedURLException e) { 
    } catch (IOException e) { 
} 
t.setText(urls.get(0)); // My TextFile has 3 lines 

... それはドメイン名までとすることができますか?代わりにIPが必要ですか? whileループが実行されていないことが分かりました。 whileループにt.setText *を置くとエラーはなく、TextViewは空です。 LogCat Error:http://textuploader.com/5iijrそれは行をハイライト表示t.setText(urls.get(0));

ありがとうございました!!!

+3

は「mydomainname.de/test.txt」は有効なURLではありません別のスレッドを使用して、それを呼びましょう。その結果、 'URL'コンストラクタはあなたが完全に無視している' MalformedURLException'を投げます。 2番目の結果として、 'urls'のあなたのリストは満たされず、空のままです。 – Seelenvirtuose

+0

私のリストがどれくらい満たされていないかで、有効な正式リンクを削除しましたか?私はそれを得ていない。 @Seelenvirtuose – killertoge

+0

変数 'urls'を空のリストで初期化しています。次にtry-catchブロックがあり、最初に_malformed_ URLを持つ 'URL'オブジェクトを作成します。だからあなたは例外を得るでしょう。そして、あなたの変数 'urls'は変更されません。それ以上ではない。結論:例外を飲み込まないでください!少なくともスタックトレースを出力する: 'e.printStackTrace()'。 – Seelenvirtuose

答えて

4

情報を取得するためのHttpURLConnectionまたはOKHTTP要求を使用してみてください、ここではこれを試してみてください。

は常にNetworkOnMainThread例外

new Thread(new Runnable(){ 

    public void run(){ 


    ArrayList<String> urls=new ArrayList<String>(); //to read each line 
    //TextView t; //to show the result, please declare and find it inside onCreate() 



    try { 
     // Create a URL for the desired page 
     URL url = new URL("http://somevaliddomain.com/somevalidfile"); //My text file location 
     //First open the connection 
     HttpURLConnection conn=(HttpURLConnection) url.openConnection(); 
     conn.setConnectTimeout(60000); // timing out in a minute 

     BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); 

     //t=(TextView)findViewById(R.id.TextView1); // ideally do this in onCreate() 
     String str; 
     while ((str = in.readLine()) != null) { 
      urls.add(str); 
     } 
     in.close(); 
    } catch (Exception e) { 
     Log.d("MyTag",e.toString()); 
    } 

    //since we are in background thread, to post results we have to go back to ui thread. do the following for that 

    Activity.this.runOnUiThread(new Runnable(){ 
     public void run(){ 
      t.setText(urls.get(0)); // My TextFile has 3 lines 
     } 
    }); 

    } 
}).start(); 
+0

urls.get(0)は必要に応じて最初の行のみを取得します。 – Kushan

0
にスローされますバックグラウンドスレッドで他のAndroidのネットワーキングのどんなことを

これを試してみてください。わたしにはできる。

private static String readText(){ 
    String link="http://.../file.txt"; 
    ArrayList<String> al=new ArrayList<>(); 

    try{ 
     URL url = new URL(link); 
     URLConnection conn = url.openConnection(); 
     conn.setDoOutput(true); 
     conn.connect(); 

     InputStream is = conn.getInputStream(); 
     InputStreamReader isr = new InputStreamReader(is, "UTF-8"); 
     BufferedReader br = new BufferedReader(isr); 
     String line; 

     try { 
      while ((line = br.readLine()) != null) { 
       al.add(line); 
      } 
     } finally { 
      br.close(); 
     } 
    }catch (IOException e){ 
     e.printStackTrace(); 
    } 
    return al.get(0); 
} 

ので、

t.setText(readText()); 
1

の1-)マニフェストファイルにインターネットのアクセス許可を追加します。

2-)別のスレッドでコードを起動していることを確認してください。

ここは私のためにうまくいくスニペットです。

public List<String> getTextFromWeb(String urlString) 
    { 
     URLConnection feedUrl; 
     List<String> placeAddress = new ArrayList<>(); 

     try 
     { 
      feedUrl = new URL(urlString).openConnection(); 
      InputStream is = feedUrl.getInputStream(); 

      BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));   
      String line = null; 

      while ((line = reader.readLine()) != null) // read line by line 
      { 
       placeAddress.add(line); // add line to list 
      } 
      is.close(); // close input stream 

      return placeAddress; // return whatever you need 
     } 
     catch (Exception e) 
     { 
      e.printStackTrace(); 
     } 

     return null; 
    } 

私たちのリーダー機能は準備ができている、のは

  new Thread(new Runnable() 
      { 
       public void run() 
       { 
        final List<String> addressList = getTextFromWeb("http://www.google.com/sometext.txt"); // format your URL 
        runOnUiThread(new Runnable() 
        { 
         @Override 
         public void run() 
         { 
          //update ui 
         } 
        }); 
       } 
      }).start(); 
+0

これはうまくいきますが、あなたが追加したアップデートのUiコメントを記入するのに時間がかかっていました。私はここでそれを指摘して欲しいと思います。 'StringBuilder sb = new StringBuilder(); (String s:placeAddress) { sb.append(s); sb.append( "\ n"); } テキストビューlyricsTextView =(TextView)getView()。findViewById(R.id.lyricsTextView); lyricsTextView.setText(sb.toString()); ' –

関連する問題