mesopotamia
mesopotamia

Reputation: 393

Android load images into viewpager from web

I am loading images from drawable but it is not effective now i want to load images from web but i am stucked. I realy search for solutions but i cant success. There is my Custom Adapter class:

int[] imageId = {R.drawable.first, R.drawable.second, R.drawable.third, R.drawable.fourth, R.drawable.fifth};

        public Object instantiateItem(ViewGroup container, int position) {
        global_position=position;

        LayoutInflater inflater = ((Activity)context).getLayoutInflater();

        View viewItem = inflater.inflate(R.layout.image_item, container, false);
        imageView = (ImageView) viewItem.findViewById(R.id.imageView);
        imageView.setImageResource(imageId[position]);
        ((ViewPager)container).addView(viewItem);
        return viewItem;
    }

How can a turn this it can download images from web and load view pager.

Upvotes: 1

Views: 364

Answers (1)

Hedegare
Hedegare

Reputation: 2047

You can use an AsyncTask to do that job without crashing your app.

class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    ImageView myImage //your image url;

    public DownloadImageTask(ImageView myImage) {
        this.myImage = myImage;
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap mIcon = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return mIcon;
    }

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

To use this class just instanciate it like the others.

new DownloadImageTask((ImageView) findViewById(R.id.your_image_viewer))
            .execute(imageURL);

Upvotes: 1

Related Questions