読者です 読者をやめる 読者になる 読者になる

AsyncTaskを使って非同期で画像をダウンロードし、適当に表示するサンプル

java android
  • 画像の表示にはImageViewを使う。
  • HTTPリクエストにはURLConnectionを使う。
  • BitmapデータのセットにはsetImageBitmapメソッドを使う。


package get.image;

import java.io.*;
import java.net.*;

import android.app.Activity;
import android.os.Bundle;
import android.os.AsyncTask;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.LinearLayout;
import android.widget.ImageView;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class GetImage extends Activity
{
    ImageView imageView;
    getImageData getImageData;
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        LinearLayout linearLayout = new LinearLayout(this);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        setContentView(linearLayout);
        
        imageView = new ImageView(this);
        
        getImageData = new getImageData(linearLayout, imageView);
        getImageData.execute();
    }
    
    class getImageData extends AsyncTask<String, Integer, Bitmap>{
        
        private ImageView imageView;
        private LinearLayout linearLayout;
        
        public getImageData(LinearLayout linearLayout, ImageView imageView){
            super();
            this.imageView = imageView;
            this.linearLayout = linearLayout;
        }
        
        @Override
        protected Bitmap doInBackground(String... param){
            Bitmap bitmap;
            
            try {
                //URL url = new URL("http", "suzuki.toshinari.jp", "/images/thumbnail_codaholic.org.jpg");
                URL url = new URL("http://suzuki.toshinari.jp/images/thumbnail_codaholic.org.jpg");
                //HttpURLConnection urlcon = (HttpURLConnection)url.openConnection();
                InputStream inputStream = url.openStream();
                bitmap = BitmapFactory.decodeStream(inputStream);
                return bitmap;
            } catch (IOException ex) {
                Logger.getLogger(GetImage.class.getName()).log(Level.SEVERE, null, ex);
            }
            
            return null;
        }
        
        @Override
        protected void onPostExecute(Bitmap result){
            
            /*
            this.imageView.setImageBitmap(result);
            this.linearLayout.addView(this.imageView);
            */
            
            imageView.setImageBitmap(result);
            linearLayout.addView(imageView);

        }
    }
}