2015-06-21 70 views
0

我想從我的Dropbox下載文件,但我的應用程序崩潰,錯誤日誌講述了http錯誤,我做錯了什麼?錯誤日誌只是說「產生的原因:android.os.NetworkOnMainThreadException」然後列出HTTP錯誤Android http錯誤

private final String PATH = "/data/data/com.emiliogaines.fuelfinder/shared_prefs/"; //put the downloaded file here 


    public void DownloadFromUrl(String fileName) { //this is the downloader method 
     try { 

      URL url = new URL("https://www.dropbox.com/s/1793397jyxorw6g/testDoc.xml?dl=0"); 
      File file = new File(PATH + fileName); 

      long startTime = System.currentTimeMillis(); 
      Log.d("ImageManager", "download begining"); 
      Log.d("ImageManager", "download url:" + url); 
      Log.d("ImageManager", "downloaded file name:" + fileName); 
        /* 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); 

        /* 
        * Read bytes to the Buffer until there is nothing more to read(-1). 
        */ 
      ByteArrayBuffer baf = new ByteArrayBuffer(50); 
      int current = 0; 
      while ((current = bis.read()) != -1) { 
       baf.append((byte) current); 
      } 

        /* Convert the Bytes read to a String. */ 
      FileOutputStream fos = new FileOutputStream(file); 
      fos.write(baf.toByteArray()); 
      fos.close(); 
      Log.d("ImageManager", "download ready in" 
        + ((System.currentTimeMillis() - startTime)/1000) 
        + " sec"); 

     } catch (IOException e) { 
      Log.d("ImageManager", "Error: " + e); 
     } 

    } 

回答

0

一個NetworkOnMainThreadException的很多意味着你正在試圖訪問網絡的主線程上,嘗試創建一個新的線程和訪問那裏的網絡。

當應用程序嘗試在其主線程上執行聯網操作時引發的異常。 (http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

+0

好的謝謝!但我真的不懂線程,你可以編輯代碼或什麼?我從來沒有讓他們工作 –

+0

試試這個鏈接http://android-developers.blogspot.de/2009/05/painless-threading.html,那裏有如何在android中執行線程的例子。像'new Thread(new Runnable(){public void run(){...}})。start();'然後將上面的代碼包含在'run()'方法內 –