2013-04-26 104 views
2

我想獲取Internet txt文件的內容。當我用模擬器打開它時,我收到此消息從網址讀取文件

「不幸的是,應用程序已停止」。

如果刪除「http://」,但它沒有讀取任何內容並且變成null,沒有任何反應。怎麼了?如何讀取上面的網址?我已經添加了許可。

這是我更改的整個代碼,但仍然有相同的錯誤。我做了什麼錯誤? http://dforum.zxq.net/code.txt

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
new AsyncTask<Void, Void, Void>() { 

     @Override 
     protected Void doInBackground(Void... arg0) { 



      try { 
       URL url = new URL("http://dforum.zxq.net/myfile.txt"); 

       BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); 
       String str; 
       while ((str = in.readLine()) != null) { 
        Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();  
        // str is one line of text; readLine() strips the newline character(s) 
       } 
       in.close(); 
      } catch (MalformedURLException e) { 
      } catch (IOException e) { 
      } 




      return null; 
      // TODO Auto-generated method stub 

     } 


    }.execute(); 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.main, menu); 
    return true; 
} 

}

+0

請添加您的logcat輸出。 – rekire 2013-04-26 20:59:20

+0

http://dforum.zxq.net/log.txt – 2013-04-26 21:13:33

回答

1

確保你不這樣做,在UI線程上,並檢查是否有互聯網的權限。

這兩種情況都可能導致異常,導致您的應用崩潰。

下面是關於如何防止GUI線程做網絡運營的例子:

new AsyncTask<Void, Void, Void>{ 
    @Override 
    protected Void doInBackground(Void... params) { 

     // add your try catch block here. 

     return null; 
    } 
}.execute(); 
+0

權限 <使用權限android:name =「android.permission .INTERNET「/> – 2013-04-26 21:08:31

+0

這是我的permisions,但我不知道什麼是UI線程。我仍然得到這個錯誤 – 2013-04-26 21:09:20

+0

好吧,它會是線程的東西。將你的try catch塊封裝在一個異步任務中。我會將這些添加到我的答案中,請稍等片刻。 – rekire 2013-04-26 21:10:35

0

確保你運行它的AsyncTask內服用此過程中關閉主UI線程。看看這個教程:http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/。更具體地說,查看那裏的JSONParser類。

UPDATE

你調用一個while循環,我認爲這是它崩潰的原因Toast。替換爲Log.d()System.out.println()

+0

我做過所有你說的也加上這個 我寫了上面的整個代碼?那麼爲什麼它再次關閉? – 2013-04-26 22:18:18

+0

如果日誌輸出不同,請更新您的答案。 – 2013-04-26 22:49:04

+0

嘗試爲AsyncTask創建一個內部類,而不像上面鏈接的教程那樣。 – 2013-04-26 22:49:54