Visualizar una imagen de internet en Android

Si necesitamos tener una aplicación cuyos contenidos sean dinámicos y no estar liberando actualizaciones masivas todos los días y molestar al usuario podemos descargar dicho contenido de internet. Hoy veremos una forma media sencilla de como visualizar una imagen que se encuentra en internet solo introduciendo su URL. En este ejemplo, la URL la proporcionamos nosotros desde un editText pero tranquilamente podría ser una variable o un dato almacenado en una bd. Hay que recordar que dicha URL debe tener el protocolo http:// delante sino el ejemplo no funciona.

1) Primero debemos preparar el layout donde trabajaremos.

Agregamos un edittext, un button y un imageView

<EditText android:layout_height="wrap_content"
android:id="@+id/editText1" android:layout_width="match_parent">
<Button android:id="@+id/button1" android:text="Magia"
<ImageView android:layout_height="wrap_content" android:src="@drawable/icon"
android:id="@+id/imageView1" android:layout_width="wrap_content">



2) Creamos una clase Java cuyo setContentView será este layout y “levantamos” dichos componentes y los almacenamos en nuestras variables globales.


private Button btn;
private ImageView m_imageView;

private EditText inputUrl;

/** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState)
        inputUrl = (EditText)findViewById(;
        m_imageView = (ImageView)findViewById(;
3) Establecer el comportamiento del botón, que descargara la imagen.
No se asusten en este paso porque tirara un error que todavía falta codigo
por explicar.

btn.setOnClickListener(new OnClickListener()
     public void onClick(View arg0)
            String url=inputUrl.getText().toString();
            if (url.length()>0)
               new DownloadImageTask().execute(url);

4) Crear un clase inside de la clase que estamos trabajando.

 class DownloadImageTask extends AsyncTask<String, Void, Drawable>

          final ProgressDialog progressDialog = new ProgressDialog(main.this);

            protected void onPreExecute()
                progressDialog.setMessage("Cargando imagen...");

            protected Drawable doInBackground(String... urls)
                Log.d("DEBUG", "drawable");

                return downloadImage(urls[0]);


            protected void onPostExecute(Drawable imagen)


 * Devuelve una imagen desde una URL
 * @param url Url de la imagen
 * @return Una imagen
            private Drawable downloadImage(String imageUrl)
                    URL url = new URL(imageUrl);
                    InputStream is = (InputStream)url.getContent();
                    return Drawable.createFromStream(is, "src");
                catch (MalformedURLException e)
                    return null;
                catch (IOException e)
                    return null;

Expliquemos un poco el codigo. Lo primero que hacemos es crear una tarea asíncrona. ¿Que es una tarea asíncrona? Es un hilo de ejecución adicional a nuestra aplicación para realizar una tarea que puede (o no) demorarse demasiado. Con este hilo, la aplicación funciona correctamente mientras este hilo hace su trabajo. Esta AsyncTask tiene cuatro métodos principales.

  1. onPreExecute: antes de ejecutarse. Seteamos el titulo, el mensaje y empezamos a mostrar el progress dialog.
  2. doInBackground: la tarea propiamente dicha la haremos acá. En nuestro caso descargar la imagen según la url que le hayamos pasado cuando hacemos click.
  3. onPostExecute: cuando el hilo finalizo cerramos el progress dialog y seteamos la imagen devuelta a nuestro imageView.
  4. downloadImage: [este método lo creamos nosotros. Los restantes tres son obligatorios por la implementación de la clase] acá descargamos la imagen haciendo una petición http

También deben agregar un permiso de uso de internet dentro del manifiesto (luego del tag application)

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

Aqui un video de como debería funcionar el ejemplo:

Cualquier duda o comentario del ejemplo no duden en dejar un comentario en esta entrada.

13 thoughts on “Visualizar una imagen de internet en Android

  1. Just one more great way to save lots of income upon auto tires is always to employ payless coupon codes. You can choose a lot of discount coupons regarding different elements. You’ll find inexpensive exhaust coupon codes and affordable auto deals while successfully which can be employed for car repairs. A price reduction car voucher might be incredibly handy if you’re holding serp issues. Coupons are a great way in order to maintain bucks high are a variety of discount codes easily available on the market. The highest approach to discover a discount that you can use is to appear and feel on their behalf in the magazine. You may also learn coupon codes for the on the web. It is possible to track down discount codes on-line or perhaps get very simple computer discount coupons from a site. Payless coupon

  2. The talk within the finest worn cellular phone for traffic is built to be equalize any more exceedingly asserted amidst consumers. There are lots of brands from which to choose with a the whole kit of models. Then you indigence capabilities to take into account, and also battery. In the end you obligated to distinguish the inseparable that’s kind on the side of you, and also fit’s your own special taste of style. The current overcome three hottest employed cellular phones elbow would be the BlackBerry Bead, Your Apple IPhone, as luckily as the Motorola talkabout Blade. All three or more of such are terrific candidates and each has their acutely own durability as articulately as fragile spots. We wishes look at each solitary of these individually so that you can choose repayment for yourself which of such you imagine disposition be best.
    Used cellphones for sale

  3. The talk within the finest toughened cellular phone repayment for sale is built to be unbiased now fiercely asserted amidst consumers. There are lots of brands from which to opt with a masses of models. Then you need capabilities to clutch into account, and also battery. In the motive you must distinguish the one that’s kind with a view you, and also spasm’s your own special taste of style. The fashionable best three hottest employed cellular phones elbow would be the BlackBerry Bead, Your Apple IPhone, as luckily as the Motorola talkabout Blade. All three or more of such are terrific candidates and each has their entirely own durability as articulately as unsubstantial spots. We will look at each people of these separately so that you can decide seeking yourself which of such you credence in will be best.
    Used cellphones for sale

  4. Have you ever considered adding more videos to your blog site posts to maintain the readers more entertained? I indicate I just study through the entire write-up of yours and it was really excellent but since I’m more of a visual learner,I found that to be more helpful properly let me understand how it turns out! I love what you guys are always up as well. These clever work and reporting! Keep up the wonderful works guys I’ve added you guys to my blogroll. That is a excellent article thanks for sharing this informative information.. I will visit your blog regularly for some latest post.

  5. You really make it seem so easy along with your presentation however I in finding this topic to be actually one thing that I believe I’d never understand. It kind of feels too complicated and extremely extensive for me. I’m taking a look forward for your next put up, I’ll attempt to get the dangle of it!

  6. My partner and I stumbled over here from a different web address and thought I might as well check things out. I like what I see so now i’m following you. Look forward to looking over your web page yet again.

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *