Thursday, 30 September 2010

Android:The easiest way to load image from URL

The easiest way to download image from URL is to use method Drawable.createFromStream:

main.xml:
<linearlayout android:id="@+id/LinearLayout01" 
android:layout_height="fill_parent" 
android:layout_width="fill_parent" 
xmlns:android="http://schemas.android.com/apk/res/android">
<imageview android:id="@+id/ImageView1" 
android:layout_height="wrap_content" 
android:layout_width="wrap_content">
</imageview></linearlayout>


Java file:
import java.io.InputStream;
import java.net.URL;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.ImageView;

public class ImageFromUrlExample extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        ImageView imgView =(ImageView)findViewById(R.id.ImageView1);
        Drawable drawable = loadImageFromWeb("http://www.example.com/android.png");
        imgView.setImageDrawable(drawable);

    }

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

6 comments:

  1. Hi,

    This works for me most of the time, but createFromStream() sometimes returns null on certain URLs. What can I do?

    Thanks,
    gb

    ReplyDelete
  2. Hi,
    here wrote that it's SDK bug
    http://stackoverflow.com/questions/4601352/createfromstream-in-android-returning-null-for-certain-url

    ReplyDelete
  3. Yes, I discovered that yesterday as well. I can't believe it hasn't been fixed yet. I used a workaround that seems t work okay.

    ReplyDelete
  4. heyy do u have any idea what second parameter describe here "src" ?

    ReplyDelete
  5. Hi, answer - "it is used when creating nine-patch images from the resource, but not when creating a regular Bitmap" from here - http://stackoverflow.com/questions/6122599/android-drawable-createfromstreamis-srcname-whats-the-2nd-parameter-meanin

    ReplyDelete
  6. i want to load image to an imageview with jpeg extension... need help ????

    ReplyDelete