Friday, August 10, 2012

Load image from URL to Android

Once I needed to display an image loading from URL in my Android application. After referring some resources I was success. Here I post what I did. This is for future references. I did this for Android 2.2 platform.

This Android application load an image from a server using HttpURLConnection and show it in image view when you click load image button.
(I have used  image located here http://www.codeincloud.tk/play.png)

Download this project


Here is the layout file.

<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btn_imgload"
        android:layout_width="208dp"
        android:layout_height="wrap_content"
        android:layout_x="57dp"
        android:layout_y="322dp"
        android:text="Load Image" />

    <ImageView
        android:id="@+id/imageview"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_x="131dp"
        android:layout_y="179dp" />

</AbsoluteLayout>

This is the java code

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
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.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class LoadImageActivity extends Activity {
 
 ImageView image_view;
 Button btnLoadImg ;
    final static String imageLocation="http://www.codeincloud.tk/play.png"; //Use any image location. 
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        image_view = (ImageView)findViewById(R.id.imageview);
        btnLoadImg = (Button)findViewById(R.id.btn_imgload);
        
        btnLoadImg.setOnClickListener(loadImage);
    }
    
    
    View.OnClickListener loadImage = new View.OnClickListener(){
     public void onClick(View view) {
         loadImage(imageLocation);
            }
     };
    
     Bitmap bitmap;
    void loadImage(String image_location){
      
          URL imageURL = null;
          
          try {
           imageURL = new URL(image_location);
           } 
          
          catch (MalformedURLException e) {
              e.printStackTrace();
           }
          
          try {
           HttpURLConnection connection= (HttpURLConnection)imageURL.openConnection();
           connection.setDoInput(true);
           connection.connect();
              InputStream inputStream = connection.getInputStream();
               
              bitmap = BitmapFactory.decodeStream(inputStream);//Convert to bitmap
              image_view.setImageBitmap(bitmap);
          }
          catch (IOException e) {
              
               e.printStackTrace();
          }
    }
  }

Add internet permission to Manifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="tutorial.imageload"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk android:minSdkVersion="8" />
    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".LoadImageActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>
</manifest>

14 comments:

  1. Wow! Ιn the enԁ I got a blοg from ωhere I be able to in fаct get usеful factѕ concerning my
    studу and knoωledge.
    Also visit my webpage ... www.charlottefrench.org

    ReplyDelete
  2. I simply couldn't leave your website before suggesting that I really enjoyed the usual information a person supply in your visitors? Is gonna be back ceaselessly to inspect new posts
    Have a look at my page ; make money online with google there

    ReplyDelete
  3. I'm not sure where you are getting your information, but good topic. I needs to spend some time learning much more or understanding more. Thanks for fantastic information I was looking for this info for my mission.
    Here is my site - fire science degree careers

    ReplyDelete
  4. what do i need to do to save the image internally in the phone(not SD card) before displaying the image?
    because in my app, I want to get the image from the server first time, after that i want to save the image locally for future uses.

    ReplyDelete
  5. Goοd ωay of desсribing, and gοοd рiеcе of writing to obtain
    data about my pгeѕentation subject matter, which
    i аm gоing to delivеr in university.
    Stop by my weblog :: etched photos

    ReplyDelete
  6. Goοd daу! Would you mind if I shаre yοur blog with my zуnga grоup?
    Thеге's a lot of folks that I think would really enjoy your content. Please let me know. Thanks
    Feel free to surf my weblog ... laser pictures

    ReplyDelete
  7. Αn intriguing discusѕion is definitely ωоrth comment.
    I belieѵe that yοu ought to publіsh more
    about thіs subject matteг, it may not be
    a taboo subjeсt but generally people dο not speak аbout these issues.
    To the next! Many thankѕ!!
    Check out my web-site ... buy crystal

    ReplyDelete
  8. І love looκing through аn aгtісlе that cаn makе men and women think.
    Alsо, thanks fοr аllowing me to cοmmеnt!
    Feel free to surf my web blog ; crystal pictures

    ReplyDelete
  9. Thank you so much! That did the trick, you saved me more endless hours of searching for a fix.






    Image Processing Company in Chennai

    ReplyDelete
  10. Hi there,

    I've been trying to implement the code, but the image does not show at all on the screen. I've tried using more than one files to be loaded without any success. Do you have any idea why this could be happening, I mean, I put the exact code on my eclipse and still have no image. I've tried too may exameples on the web and neither seems to be working. Also, there are no errors shown.

    thanks in advance

    ReplyDelete
  11. Hi there,

    I've been trying to implement the code, but the image does not show at all on the screen. I've tried using more than one files to be loaded without any success. Do you have any idea why this could be happening, I mean, I put the exact code on my eclipse and still have no image. I've tried too may exameples on the web and neither seems to be working. Also, there are no errors shown.

    thanks in advance

    ReplyDelete
  12. how can i insert image to apache tomcat running on local computer to store that image in database using webservice (ksop lib.)from android thanks.

    ReplyDelete
  13. Nice Tutorial.i would like to know how to show bunch of images loaded from server on app using this?

    ReplyDelete
  14. Nice Tutorial.can you tell me how to show lot of images ie using xml with above eg?

    ReplyDelete