2014-03-31 50 views
1

我試圖使用android模擬器從服務器下載圖像。看來,在下載工作,但我不能讓下載的圖像。而我得到這個錯誤:Android:從服務器下載文件無法解碼流

Unable to decode stream: java.io.FileNotFoundException: /storage/sdcard/downloadedfile.jpg: open failed: ENOENT (No such file or directory) 

而且這是我使用的代碼:

public class DownloadActivity extends Activity { 
// button to show progress dialog 
Button btnShowProgress; 

// Progress Dialog 
private ProgressDialog pDialog; 
ImageView my_image; 
// Progress dialog type (0 - for Horizontal progress bar) 
public static final int progress_bar_type = 0; 



// File url to to download  
     private static String file_url = `"http://10.0.2.2:8080/TestAndroid/DownloadServlet/Desert.jpg";` 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 


    // show progress bar button 
    btnShowProgress = (Button) findViewById(R.id.btnProgressBar); 
    // Image view to show image after downloading 
    my_image = (ImageView) findViewById(R.id.my_image); 
    /** 
    * Show Progress bar click event 
    * */ 
    btnShowProgress.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // starting new Async Task 
      new DownloadFileFromURL().execute(file_url); 
     } 
    }); 
} 

/** 
* Showing Dialog 
* */ 
@Override 
protected Dialog onCreateDialog(int id) { 
    switch (id) { 
    case progress_bar_type: // we set this to 0 
     pDialog = new ProgressDialog(this); 
     pDialog.setMessage("Downloading file. Please wait..."); 
     pDialog.setIndeterminate(false); 
     pDialog.setMax(100); 
     pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
     pDialog.setCancelable(true); 
     pDialog.show(); 
     return pDialog; 
    default: 
     return null; 
    } 
} 

/** 
* Background Async Task to download file 
* */ 
class DownloadFileFromURL extends AsyncTask<String, String, String> { 

    /** 
    * Before starting background thread 
    * Show Progress Bar Dialog 
    * */ 
    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     showDialog(progress_bar_type); 
    } 

    /** 
    * Downloading file in background thread 
    * */ 
    @Override 
    protected String doInBackground(String... f_url) { 
     int count; 
     try { 
      URL url = new URL(f_url[0]); 
      URLConnection conection = url.openConnection(); 
      conection.connect(); 
      // this will be useful so that you can show a tipical 0-100% progress bar 
      int lenghtOfFile = conection.getContentLength(); 

      // download the file 
      InputStream input = new BufferedInputStream(url.openStream(), 8192); 

      // Output stream 
      // OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg"); 

      byte data[] = new byte[1024]; 

      long total = 0; 
      long startTotalTime = System.currentTimeMillis(); 
      long passedTime =0; 
      long previosTime=0; 

      while ((count = input.read(data)) != -1) { 
       total += count; 
       long endtTime = System.currentTimeMillis(); 
       long passed; 
       passedTime =endtTime - startTotalTime; 
       // passed=passedTime -previosTime ; 
       // previosTime = passed ; 

       // publishing the progress.... 
       // After this onProgressUpdate will be called 
       publishProgress(""+(int)((total*100)/lenghtOfFile)); 
       Log.i("log_lenghtOfFile",lenghtOfFile+""); 
       Log.i("log_total",total+""); 
       Log.i("log_ourcentage",(int)((total*100)/lenghtOfFile)+""); 
       Log.i("log_passed_time",passedTime +""); 
       calculDebitdescendant(total, lenghtOfFile); 
       // Log.i("log_Debit",passedTime +""); 
       // writing data to file 
       // output.write(data, 0, count); 
      } 
      long endTotalTime = System.currentTimeMillis(); 
      Log.i("log_Total_passed_time",endTotalTime-startTotalTime +""); 

      // flushing output 
      // output.flush(); 

      // closing streams 
     // output.close(); 
      input.close(); 

     } catch (Exception e) { 
      Log.e("Error***: ", e.getMessage()); 
     } 

     return null; 
    } 
    public void calculDebitdescendant(long bytesAvailable,long TotalSize){ 
     long bytesAvailable1 = bytesAvailable; 
     long TotalSize1 = TotalSize; 
     Log.i("bytesAvailable",bytesAvailable1 +"fonction"); 
     Log.i("log_ourcentage",(int)(((TotalSize1-bytesAvailable1)*100)/TotalSize1)+"% "); 
    } 

    /** 
    * Updating progress bar 
    * */ 
    protected void onProgressUpdate(String... progress) { 
     // setting progress percentage 
     pDialog.setProgress(Integer.parseInt(progress[0])); 
    } 

    /** 
    * After completing background task 
    * Dismiss the progress dialog 
    * **/ 
    @Override 
    protected void onPostExecute(String file_url) { 
     // dismiss the dialog after the file was downloaded 
     dismissDialog(progress_bar_type); 

     // Displaying downloaded image into image view 
     // Reading image path from sdcard 
     String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.jpg"; 
     Log.i("imagePath", imagePath); 
     // setting downloaded into image view 
     my_image.setImageDrawable(Drawable.createFromPath(imagePath)); 
    } 

} 

}

PS:模擬器的SD卡不包含該圖像,我把所有的權限。 如果有人知道錯誤的來源,請告訴我。謝謝。

+1

你加AndroidManifest.xml文件中的'android.permission.WRITE_EXTERNAL_STORAGE'權限? –

+0

是的,我做了,寫和讀太多的權限。 – Amina

+1

如果外部存儲不存在或不可寫入,則可能發生這種情況。 [這裏是一個教程](http://developer.android.com/training/basics/data-storage/files.html)關於在Android中創建文件,有一些方法示例用於測試卷是否可用。 –

回答

1

我編輯的代碼,我可以從服務器下載圖片到emulator.I剛啓用寫的SD卡(我把他們的意見)

public class DownloadActivity extends Activity { 
// button to show progress dialog 
Button btnShowProgress; 

// Progress Dialog 
private ProgressDialog pDialog; 
ImageView my_image; 
// Progress dialog type (0 - for Horizontal progress bar) 
public static final int progress_bar_type = 0; 

// File url to to download  
    // private static String file_url = "http://192.168.1.106:8080/TestAndroid/DownloadServlet/Desert.jpg"; 
    private static String file_url = "http://10.0.2.2:8080/TestAndroid/DownloadServlet/Desert.jpg"; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 


    // show progress bar button 
    btnShowProgress = (Button) findViewById(R.id.btnProgressBar); 
    // Image view to show image after downloading 
    my_image = (ImageView) findViewById(R.id.my_image); 
    /** 
    * Show Progress bar click event 
    * */ 
    btnShowProgress.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // starting new Async Task 
      new DownloadFileFromURL().execute(file_url); 
     } 
    }); 
} 

/** 
* Showing Dialog 
* */ 
@Override 
protected Dialog onCreateDialog(int id) { 
    switch (id) { 
    case progress_bar_type: // we set this to 0 
     pDialog = new ProgressDialog(this); 
     pDialog.setMessage("Downloading file. Please wait..."); 
     pDialog.setIndeterminate(false); 
     pDialog.setMax(100); 
     pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
     pDialog.setCancelable(true); 
     pDialog.show(); 
     return pDialog; 
    default: 
     return null; 
    } 
} 

/** 
* Background Async Task to download file 
* */ 
class DownloadFileFromURL extends AsyncTask<String, String, String> { 

    /** 
    * Before starting background thread 
    * Show Progress Bar Dialog 
    * */ 
    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     showDialog(progress_bar_type); 
    } 

    /** 
    * Downloading file in background thread 
    * */ 
    @Override 
    protected String doInBackground(String... f_url) { 
     int count; 
     try { 
      URL url = new URL(f_url[0]); 
      URLConnection conection = url.openConnection(); 
      conection.connect(); 
      // this will be useful so that you can show a tipical 0-100% progress bar 
      int lenghtOfFile = conection.getContentLength(); 

      // download the file 
      InputStream input = new BufferedInputStream(url.openStream(), 8192); 

      // Output stream 
      OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg"); 

      byte data[] = new byte[1024]; 

      long total = 0; 
      long startTotalTime = System.currentTimeMillis(); 
      long passedTime =0; 
      long previosTime=0; 

      while ((count = input.read(data)) != -1) { 
       total += count; 
       long endtTime = System.currentTimeMillis(); 
       long passed; 
       passedTime =endtTime - startTotalTime; 
       // passed=passedTime -previosTime ; 
       // previosTime = passed ; 

       // publishing the progress.... 
       // After this onProgressUpdate will be called 
       publishProgress(""+(int)((total*100)/lenghtOfFile)); 
       Log.i("log_lenghtOfFile",lenghtOfFile+""); 
       Log.i("log_total",total+""); 
       Log.i("log_ourcentage",(int)((total*100)/lenghtOfFile)+""); 
       Log.i("log_passed_time",passedTime +""); 
       calculDebitdescendant(total, lenghtOfFile); 
       // Log.i("log_Debit",passedTime +""); 
       // writing data to file 
       output.write(data, 0, count); 
      } 
      long endTotalTime = System.currentTimeMillis(); 
      Log.i("log_Total_passed_time",endTotalTime-startTotalTime +""); 

      // flushing output 
      output.flush(); 

      // closing streams 
      output.close(); 
      input.close(); 

     } catch (Exception e) { 
      Log.e("Error***: ", e.getMessage()); 
     } 

     return null; 
    } 
    public void calculDebitdescendant(long bytesAvailable,long TotalSize){ 
     long bytesAvailable1 = bytesAvailable; 
     long TotalSize1 = TotalSize; 
     Log.i("bytesAvailable",bytesAvailable1 +"fonction"); 
     Log.i("log_ourcentage",(int)(((TotalSize1-bytesAvailable1)*100)/TotalSize1)+"% "); 
    } 

    /** 
    * Updating progress bar 
    * */ 
    protected void onProgressUpdate(String... progress) { 
     // setting progress percentage 
     pDialog.setProgress(Integer.parseInt(progress[0])); 
    } 

    /** 
    * After completing background task 
    * Dismiss the progress dialog 
    * **/ 
    @Override 
    protected void onPostExecute(String file_url) { 
     // dismiss the dialog after the file was downloaded 
     dismissDialog(progress_bar_type); 

     // Displaying downloaded image into image view 
     // Reading image path from sdcard 
     String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.jpg"; 
     Log.i("imagePath", imagePath); 
     Log.i("isExternalStorageWritable", isExternalStorageWritable() + "true"); 
     // setting downloaded into image view 
     my_image.setImageDrawable(Drawable.createFromPath(imagePath)); 
    } 

} 
public boolean isExternalStorageWritable() { 
    String state = Environment.getExternalStorageState(); 
    if (Environment.MEDIA_MOUNTED.equals(state)) { 
     Log.i("isExternalStorageWritable", "true"); 
     return true; 
    } 
    return false; 
} 

}