Displaying an Image from the web

Here is code on how to display an Image in your Android code from a URL. This is similar to the VideoView Howto that was posted ( https://sites.google.com/site/androidhowto/playing-a-movie ).

public class PhotoViewer extends Activity {
    private String path = "http://peytonhamil.com/suns.jpg";
    private ImageView imageView;

    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.photoview);
        Drawable image = ImageOperations(this, path, "image.jpg");
        imageView = new ImageView(this);
        imageView = (ImageView)findViewById(R.id.imageview);
        imageView.setImageDrawable(image);
    }

    private Drawable ImageOperations(Context ctx, String url, String saveFilename) {
        try {
            InputStream is = (InputStream) this.fetch(url);
            Drawable d = Drawable.createFromStream(is, "src");
            return d;
        } catch (MalformedURLException e) {
            return null;
        } catch (IOException e) {
            return null;
        }
    }

    public Object fetch(String address) throws MalformedURLException,IOException {
        URL url = new URL(address);
        Object content = url.getContent();
        return content;
    }
}

Don't forget to add your ImageView to the XML file.

Comments