How to show image from url in android

I browsed the Internet but could not find a working example of how to display an image from a URL.

Below is the failure code, and I can’t understand why .. Any help is much appreciated. Thank.

TesteImages.java:

package pac.image3;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;

public class TestImages extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.main);
        ImageView image = (ImageView) findViewById(R.id.test_image);

        String imageUrl = "http://www.small-world.net/_borders/small_world_logo.gif";
        try {
          ImageView i = (ImageView)findViewById(R.id.test_image);
          Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageUrl).getContent());
          i.setImageBitmap(bitmap);
          setContentView(image);
        } catch (MalformedURLException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }


    }
}

Res / layout / main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />

    <ImageView 
   android:id="@+id/test_image"
   android:src="@drawable/icon"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   />

</LinearLayout>
+3
source share
2 answers

Just use the following method to draw an image with a URL:

Drawable drawable_from_url(String url, String src_name) throws 
   java.net.MalformedURLException, java.io.IOException 
{
   return Drawable.createFromStream(((java.io.InputStream)
      new java.net.URL(url).awagetContent()), src_name);
}

Just pass the string url for the method (and for src_name of any string), and it will return a drawing object to you, and then use the image's setBckgroundDrawable () method to set the background of the image.

+7
source

. Drawable , . 100

Drawable drw =LoadImageFromWebOperations(imageUrl);
image.setImageDrawable(drw);

return  image;

private Drawable LoadImageFromWebOperations(String strPhotoUrl) 
    {
        try
        {
        InputStream is = (InputStream) new URL(strPhotoUrl).getContent();
        Drawable d = Drawable.createFromStream(is, "src name");
        return d;
        }catch (Exception e) {
        System.out.println("Exc="+e);
        return null;
        }
+2

All Articles