0

有人可以給我一個手。我如何使用AsyncTask而不是Try塊來重新使用下面的示例。如何將Android圖片下載器修改爲AsyncTask

因爲我只想從Web上下載圖像保存到SD並獲取返回的存儲路徑,所以我可以將它加載到imageView上。

我正在使用庫https://github.com/Bearded-Hen/Android-Bootstrap我有圓形縮略圖ImageView。我只能通過使用抽屜圖像來更改此視圖的圖像。這就是爲什麼我想保存的圖片第一,然後加載到這個自定義的ImageView

String filepath = ""; 
        try 
        { 
         URL url = new URL("http://d3sdoylwcs36el.cloudfront.net/VEN-virtual-enterprise-network-business-opportunities-small-fish_id799929_size485.jpg"); 
         HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 
         urlConnection.setRequestMethod("GET"); 
         urlConnection.setDoOutput(true);     
         urlConnection.connect();     
         File SDCardRoot = Environment.getExternalStorageDirectory().getAbsoluteFile(); 
         String filename="downloadedFile.png"; 
         Log.i("Local filename:",""+filename); 
         File file = new File(SDCardRoot,filename); 
         if(file.createNewFile()) 
         { 
         file.createNewFile(); 
         }     
         FileOutputStream fileOutput = new FileOutputStream(file); 
         InputStream inputStream = urlConnection.getInputStream(); 
         int totalSize = urlConnection.getContentLength(); 
         int downloadedSize = 0; 
         byte[] buffer = new byte[1024]; 
         int bufferLength = 0; 
         while ((bufferLength = inputStream.read(buffer)) > 0) 
         {     
         fileOutput.write(buffer, 0, bufferLength);     
         downloadedSize += bufferLength;     
         Log.i("Progress:","downloadedSize:"+downloadedSize+"totalSize:"+ totalSize) ; 
         }    
         fileOutput.close(); 
         if(downloadedSize==totalSize) filepath=file.getPath();  
        } 
        catch (MalformedURLException e) 
        { 
         e.printStackTrace(); 
        } 
        catch (IOException e) 
        { 
         filepath=null; 
         e.printStackTrace(); 
        } 
        Log.e(TAG, "''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''"); 
        Log.i("filepath:"," "+filepath) ; 
        //return filepath; 

我得到的文件路徑NULL值

+0

使用上述asynctask的doInBackground()方法中的代碼 –

+0

你使用發佈代碼時會遇到什麼問題? –

+0

我強烈建議使用開源解決方案來下載和顯示ImageView中的圖像。看看畢加索:https://github.com/square/picasso –

回答

1
ImageView mChart = (ImageView) findViewById(R.id.imageview); 
String URL = "http://www...anything ..."; 

mChart.setTag(URL); 
new DownloadImageTask.execute(mChart); 

任務等級:

public class DownloadImagesTask extends AsyncTask<ImageView, Void, Bitmap> { 
ImageView imageView = null; 

@Override 
protected Bitmap doInBackground(ImageView... imageViews) { 
this.imageView = imageViews[0]; 
return download_Image((String)imageView.getTag()); 
} 

@Override 
protected void onPostExecute(Bitmap result) { 
imageView.setImageBitmap(result); 
} 


private Bitmap download_Image(String url) { 
    ... 
}