java – Uploading pictures from the web to the Android application

Question:

Interested in the question of such an implementation, for example: there is a picture on the html page, how can I load it into the application and show it in the ImageView? Newbie in programming, can you tell me the resources and whether?

Answer:

A good example with inheriting the image loader from AsyncTask and defining its doInBackground () method, taken from the English SO , which took it from Android Developers, which has already removed it.

AsyncTask itself is an implementation of a short asynchronous request for the main GUI thread without having to poke around with the threads yourself.

// Показать картинку
new DownloadImageTask((ImageView) findViewById(R.id.imageView1))
            .execute("http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png");
}

public void onClick(View v) {
    startActivity(new Intent(this, IndexActivity.class));
    finish();

}

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    ImageView bmImage;

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

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap mIcon11 = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Ошибка передачи изображения", e.getMessage());
            e.printStackTrace();
        }
        return mIcon11;
    }

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

And in the manifest for the application, of course, you need to allow the download:

<uses-permission android:name="android.permission.INTERNET" />

If you need it quickly and without any asynchrony, error handling, etc.:

URL newurl = new URL(image_location_url); 
mIcon_val = BitmapFactory.decodeStream(newurl.openConnection() .getInputStream());
myImageView.setImageBitmap(mIcon_val);

For the very lazy, the one-liner on Picasso is :

Picasso.with(context).load(myImageURL).into(imageView);
Scroll to Top