2012-02-03 71 views
3

我嘗試從互聯網上下載文件,使用這種方法:下載txt文件讓應用崩潰

try { 
    URL url = new URL("http://sites.google.com/site/androidersite/text.txt"); 
    BufferedReader in =new BufferedReader(new InputStreamReader(url.openStream())); 
    String str; 
    while ((str = in.readLine()) != null) { newline character(s) 
    } 
    in.close(); 
} catch (MalformedURLException e) { 
} catch (IOException e) { 
} 

我也更新我的Android清單並添加此行:

<uses-permission android:name="android.permission.INTERNET"/> 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 

和應用程序崩潰在這條線:

BufferedReader in =new BufferedReader(new InputStreamReader(url.openStream())); 

和彈出窗口,寫日誌文件:Source not found

回答

2

此代碼是否在主應用程序線程上運行?你測試的Android版本是什麼?如果它在主(UI)線程上,那很糟糕。它可能會拋出一個「主線程上的網絡」異常,因爲他們不鼓勵你這樣做:)

你能提供一些實際的logcat崩潰輸出,或可能更多的執行代碼的上下文嗎?

+0

是的,它運行在主線程 – MTA 2012-02-03 15:43:55

+0

然後,你需要將該代碼移動到另一個線程。 'AsyncTask'可以是一個很好的選擇。以下是一些文檔:http://developer.android.com/reference/android/os/AsyncTask.html 網絡上也有很多例子。 – lyricsboy 2012-02-03 15:50:27

2

可能是相關的

http://www.javahotchocolate.com/tutorials/android.html#notfound http://stackoverflow.com/questions/4720593/source-not-found-error-in-android

  /* Open a connection to that URL. */ 
      URLConnection ucon = url.openConnection(); 

      /* 
      * Define InputStreams to read from the URLConnection. 
      */ 
      InputStream is = ucon.getInputStream(); 
      BufferedInputStream bis = new BufferedInputStream(is); 

入住這裏例如http://www.helloandroid.com/tutorials/how-download-fileimage-url-your-device