2017-04-14 72 views
2

我正在接收來自web的位圖圖像,並將其顯示在包含圖像視圖的列表視圖的項目中。
但是,這似乎在將圖像設置爲位圖對象「bmImage」時遇到了麻煩。
我該如何複製收到的位圖並將其返回?
如何從AsyncTask返回位圖?

public class DownloadListImageTask extends AsyncTask<String, Integer, Bitmap> { 
    Bitmap bmImage; 
    public DownloadListImageTask(Bitmap bmImage){ 
     this.bmImage = bmImage; 
    } 
    protected Bitmap doInBackground(String... urls){ 
     String url = urls[0]; 
     Bitmap bitmap = null; 
     try{ 
      InputStream in = new URL(url).openStream(); 
      bitmap = BitmapFactory.decodeStream(in); 
     }catch(Exception e){ 
      e.printStackTrace(); 
     } 
     return bitmap; 
    } 
    protected void onPostExecute(Bitmap result){ 
     bmImage = result.copy(result.getConfig(), true); 
    } 
} 

下面是一個使用率

Bitmap bitmap; 
new DownloadListImageTask(bitmap).execute(url); 
adapter.addItem(bitmap); 
+0

請看看這個問題http://stackoverflow.com/questions/12575068/how-to-get-the-result-of-onpostexecute-to-main-因爲asynctask-is-a –

+0

你應該在後臺線程中複製,而不是在後期執行中。 – Submersed

+0

以爲我得到了足夠的信息。 thx所有。 – Yanguun

回答

2

你在你的AsyncTask創建位圖bmImage但你不要將其返回到Activity調用該AsyncTask

一兩件事你可以做的是建立在的AsyncTask監聽器:

public interface OnBitmapDownloadedListener 
{ 
    void setBitmap(Bitmap bmImage); 
} 

實現,在Activity

public class MyActivity extends AppCompatActivity implements DownloadListImageTask.OnBitmapDownloadListener

傳遞入AsyncTask構造像這樣:

new DownloadListImageTask(bitmap, this).execute(url) 

然後在postExecute()你可以叫

bmImage = result.copy(result.getConfig(), true); 
listener.setBitmap(bmImage) 
// Do stuff with the bitmap in setBitmap() 
+1

http://stackoverflow.com/questions/12575068/how-to-get-the-result-of-onpostexecute-to-main-activity-because-asynctask-is-a會給所有他需要的答案我相信。 –