36

次のコード行を Asynctask に置き換えるにはどうすればよいですか? Asynctask からビットマップをどのように「取り戻す」のですか? ありがとうございました。

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

mChart.setImageBitmap(download_Image(URL));

public static Bitmap download_Image(String url) {

        //---------------------------------------------------
        Bitmap bm = null;
        try {
            URL aURL = new URL(url);
            URLConnection conn = aURL.openConnection();
            conn.connect();
            InputStream is = conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            bm = BitmapFactory.decodeStream(bis);
            bis.close();
            is.close();
        } catch (IOException e) {
            Log.e("Hub","Error getting the image from server : " + e.getMessage().toString());
        } 
        return bm;
        //---------------------------------------------------

    }

私はこのようなことを考えました:

交換 :

mChart.setImageBitmap(download_Image(graph_URL));

次のようなもので:

mChart.setImageBitmap(new DownloadImagesTask().execute(graph_URL));

public class DownloadImagesTask extends AsyncTask<String, Void, Bitmap> {

@Override
protected Bitmap doInBackground(String... urls) {
    return download_Image(urls[0]);
}

@Override
protected void onPostExecute(Bitmap result) {
    mChart.setImageBitmap(result);              // how do I pass a reference to mChart here ?
}


private Bitmap download_Image(String url) {
    //---------------------------------------------------
    Bitmap bm = null;
    try {
        URL aURL = new URL(url);
        URLConnection conn = aURL.openConnection();
        conn.connect();
        InputStream is = conn.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        bm = BitmapFactory.decodeStream(bis);
        bis.close();
        is.close();
    } catch (IOException e) {
        Log.e("Hub","Error getting the image from server : " + e.getMessage().toString());
    } 
    return bm;
    //---------------------------------------------------
}


}

しかし、onPostExecute(Bitmap result) で mChart への参照を渡すにはどうすればよいですか ??? 何らかの方法で URL と一緒に渡す必要がありますか? すべてのコード行を置き換えたい:

mChart1.setImageBitmap(download_Image(URL_1));
mChart2.setImageBitmap(download_Image(URL_2));

似たようなもので...しかしAsynctaskの方法で!

mChart1.setImageBitmap(new DownloadImagesTask().execute(graph_URL_1));
mChart2.setImageBitmap(new DownloadImagesTask().execute(graph_URL_2));

これに対する簡単な解決策はありますか? ここで何か問題がありますか?

4

4 に答える 4

75

自分で画像をダウンロードする正当な理由がない場合は、Picassoを使用することをお勧めします。

ピカソは、画像のダウンロード、設定、およびキャッシュに関するすべての問題を解決します。簡単な例に必要なコード全体は次のとおりです。

Picasso.with(context).load(url).into(imageView);

本当に自分ですべてをやりたい場合は、以下の古い回答を使用してください。


画像がそれほど大きくない場合は、非同期タスクに匿名クラスを使用できます。これは次のようになります。

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) {
   ...
}

タグで URL を非表示にするのは少し難しいですが、この方法で埋めたい画像ビューがたくさんある場合は、呼び出し元のクラスで見栄えが良くなります。また、ListView 内で ImageView を使用していて、イメージのダウンロード中に ImageView がリサイクルされたかどうかを知りたい場合にも役立ちます。

Image がそれほど大きくない場合、タスクが基になるアクティビティへの暗黙的なポインターを持ち、ガベージ コレクターがタスクが終了するまでアクティビティ全体をメモリに保持するようになるため、私は書きました。ビットマップのダウンロード中にユーザーがアプリの別の画面に移動すると、メモリを解放できず、アプリとシステム全体の速度が低下する可能性があります。

于 2010-06-22T06:33:29.963 に答える
24

このコードを試してください:

ImageView myFirstImage = (ImageView) findViewById(R.id.myFirstImage);
ImageView mySecondImage = (ImageView) findViewById(R.id.mySecondImage);
ImageView myThirdImage = (ImageView) findViewById(R.id.myThirdImage);

String URL1 = "http://www.google.com/logos/2013/estonia_independence_day_2013-1057005.3-hp.jpg";
String URL2 = "http://www.google.com/logos/2013/park_su-geuns_birthday-1055005-hp.jpg";
String URL3 = "http://www.google.com/logos/2013/anne_cath_vestlys_93rd_birthday-1035005-hp.jpg";


myFirstImage.setTag(URL1);
mySecondImage.setTag(URL2);
myThirdImage.setTag(URL3);


new DownloadImageTask.execute(myFirstImage);
new DownloadImageTask.execute(mySecondImage);
new DownloadImageTask.execute(myThirdImage);



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) {

        Bitmap bmp =null;
        try{
            URL ulrn = new URL(url);
            HttpURLConnection con = (HttpURLConnection)ulrn.openConnection();
            InputStream is = con.getInputStream();
            bmp = BitmapFactory.decodeStream(is);
            if (null != bmp)
                return bmp;

            }catch(Exception e){}
        return bmp;
    }
}
于 2013-02-27T15:42:11.013 に答える
2

AsyncTask を拡張する内部クラスを含むクラス say..BkgProcess を作成できます。BkgProcess のインスタンス化中に、Activity クラスのコンテキストを BkgProcess コンストラクターに渡します。例:

public class BkgProcess {

 String path;   
 Context _context;

public Download(Downloader downloader, String path2){

 this.path = path2;
    _context = downloader;

}

public void callProgressDialog(){

new BkgProcess().execute((Void)null);
}
class Downloads extends AsyncTask<Void, Void, Boolean> {
    private ProgressDialog dialog = new ProgressDialog(_context);
    protected void onPreExecute(){
        dialog.setMessage("Downloading image..");
        dialog.show();
    }

    protected void onPostExecute(Boolean success) {
        dialog.dismiss();
        if(success)
            Toast.makeText(_context, "Download complete", Toast.LENGTH_SHORT).show();
    }

@Override
protected Boolean doInBackground(Void... params) {
    return(startDownload(path));

    }


public boolean startDownload(String img_url) {

// download img..

      return true;
}
}
}

あなたの活動クラスから..

BkgProcess dwn = new BkgProcess (Your_Activity_class.this, img_path);

dwn.callProgressDialog();
于 2010-06-22T13:14:30.590 に答える
1

これにより、任意のサイズの画像が取得されます...進行状況ダイアログが必要ない場合は、onPreExecute()のコードにコメントを付けるだけです。

for(int i = 0 ; i < no_of_files ; i++ )
 new FetchFilesTask().execute(image_url[i]);


private class FetchFilesTask extends AsyncTask<String, Void, Bitmap> {

    private ProgressDialog dialog = new ProgressDialog(FileExplorer.this);
    Bitmap bitmap[];
    protected void onPreExecute(){
        dialog.setMessage("fetching image from the server");
        dialog.show();
    }

     protected Bitmap doInBackground(String... args) {

             bitmap = getBitmapImageFromServer();
         return bitmap;
     }

     protected void onPostExecute(Bitmap m_bitmap) {
         dialog.dismiss();
         if(m_bitmap != null)
             //store the images in an array or do something else with all the images.   
     }
 }

public Bitmap getBitmapImageFromServer(){

    // fetch image form the url using the URL and URLConnection class
}
于 2010-06-22T10:57:57.717 に答える