Loading images from remote server/web

Basic Tutorials concerning: GUI, Views, Activites, XML, Layouts, Intents, ...

Loading images from remote server/web

Postby raquibulbari » Sat Jan 26, 2008 11:49 am

[align=center]Loading images from remote server/web[/align]

Description: In this tutorial i will show you how to load remote images to your application and bind this image to an ImageView object. HttpURLConnection is used to download the image data and BitmapFactory is used to produce the bitmap which will be used as imageview resources.

The java code goes like this:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. import java.io.IOException;
  2.  
  3. import java.io.InputStream;
  4.  
  5. import java.net.HttpURLConnection;
  6.  
  7. import java.net.MalformedURLException;
  8.  
  9. import java.net.URL;
  10.  
  11. import java.util.HashMap;
  12.  
  13. import java.util.Map;
  14.  
  15. import java.util.Random;
  16.  
  17.  
  18.  
  19. import android.app.Activity;
  20.  
  21. import android.graphics.Bitmap;
  22.  
  23. import android.graphics.BitmapFactory;
  24.  
  25. import android.os.Bundle;
  26.  
  27. import android.util.Log;
  28.  
  29. import android.view.View;
  30.  
  31. import android.widget.Button;
  32.  
  33. import android.widget.EditText;
  34.  
  35. import android.widget.ImageView;
  36.  
  37.  
  38.  
  39. public class HTTPTest extends Activity {
  40.  
  41.        
  42.  
  43.  
  44.  
  45.         ImageView imView;
  46.  
  47.         String imageUrl="http://11.0.6.23/";
  48.  
  49.         Random r;
  50.  
  51.     /** Called when the activity is first created. */  
  52.  
  53.     @Override
  54.  
  55.     public void onCreate(Bundle icicle) {
  56.  
  57.         super.onCreate(icicle);
  58.  
  59.         setContentView(R.layout.main);
  60.  
  61.         r= new Random();
  62.  
  63.        
  64.  
  65.         Button bt3= (Button)findViewById(R.id.get_imagebt);
  66.  
  67.         bt3.setOnClickListener(getImgListener);
  68.  
  69.         imView = (ImageView)findViewById(R.id.imview);
  70.  
  71.     }    
  72.  
  73.  
  74.  
  75.     View.OnClickListener getImgListener = new View.OnClickListener()
  76.  
  77.     {
  78.  
  79.  
  80.  
  81.                 @Override
  82.  
  83.                 public void onClick(View view) {
  84.  
  85.                         // TODO Auto-generated method stub
  86.  
  87.                        
  88.  
  89.                         //i tried to randomize the file download, in my server i put 4 files with name like
  90.  
  91.                         //png0.png, png1.png, png2.png so different file is downloaded in button press
  92.  
  93.                         int i =r.nextInt()%4;
  94.  
  95.                         downloadFile(imageUrl+"png"+i+".png");
  96.  
  97.                         Log.i("im url",imageUrl+"png"+i+".png");
  98.  
  99.                 }
  100.  
  101.        
  102.  
  103.     };
  104.  
  105.  
  106.  
  107.    
  108.  
  109.     Bitmap bmImg;
  110.  
  111.     void downloadFile(String fileUrl){
  112.  
  113.                 URL myFileUrl =null;           
  114.  
  115.                 try {
  116.  
  117.                         myFileUrl= new URL(fileUrl);
  118.  
  119.                 } catch (MalformedURLException e) {
  120.  
  121.                         // TODO Auto-generated catch block
  122.  
  123.                         e.printStackTrace();
  124.  
  125.                 }
  126.  
  127.                 try {
  128.  
  129.                         HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
  130.  
  131.                         conn.setDoInput(true);
  132.  
  133.                         conn.connect();
  134.  
  135.                         int length = conn.getContentLength();
  136.  
  137.  
  138.  
  139.                         InputStream is = conn.getInputStream();
  140.  
  141.                        
  142.  
  143.                         bmImg = BitmapFactory.decodeStream(is);
  144.  
  145.                         imView.setImageBitmap(bmImg);
  146.  
  147.                 } catch (IOException e) {
  148.  
  149.                         // TODO Auto-generated catch block
  150.  
  151.                         e.printStackTrace();
  152.  
  153.                 }
  154.  
  155.         }
  156.  
  157. }
  158.  
  159.  
Parsed in 0.041 seconds, using GeSHi 1.0.8.4

And here is the layout file (main.xml):
Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
  1. <?xml version="1.0" encoding="utf-8"?>
  2.  
  3. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  4.  
  5.    android:orientation="vertical"
  6.  
  7.    android:layout_width="fill_parent"
  8.  
  9.    android:layout_height="fill_parent"
  10.  
  11.    >
  12.  
  13. <TextView  
  14.  
  15.    android:layout_width="fill_parent"
  16.  
  17.    android:layout_height="wrap_content"
  18.  
  19.    android:text="Hello World, HTTPImage load test"
  20.  
  21.    />
  22.  
  23.     <Button id="@+id/get_imagebt"
  24.  
  25.    android:layout_width="wrap_content"
  26.  
  27.    android:layout_height="wrap_content"
  28.  
  29.    android:text="Get an image"
  30.  
  31.    android:layout_gravity="center"
  32.  
  33.    />  
  34.  
  35.     <ImageView id="@+id/imview"
  36.  
  37.    android:layout_width="wrap_content"
  38.  
  39.    android:layout_height="wrap_content"
  40.  
  41.    android:layout_gravity="center"
  42.  
  43.    />
  44.  
  45. </LinearLayout>
Parsed in 0.003 seconds, using GeSHi 1.0.8.4



The code is pretty simple and easy, most of you might already have done this, i am a slow learner, i tried different ways first, i tried to read the whole bytes of image data, do other trial and error method. I was confused about the Bitmap tranformation technology. Then i found that there is a built in class known as BitmapFactory, it can produce bitmap directly from stream. This saved a lot of my efforts. Hope it will come useful to you.

Happy andcoding :D
--
SHIMUL
Shimugool
User avatar
raquibulbari
Developer
Developer
 
Posts: 25
Joined: Sun Dec 16, 2007 6:31 am
Location: dhaka,bangladesh

Top

Postby plusminus » Sat Jan 26, 2008 12:07 pm

Hello shimul,

thanks for sharing your code with the community.
Loading remote images is also a part of the :src: Android Weather Forecast-Tutorial.
The code I used there is almost the same:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.      public void setRemoteImage(URL aURL) {
  2.  
  3.           try {
  4.  
  5.                URLConnection conn = aURL.openConnection();
  6.  
  7.                conn.connect();
  8.  
  9.                InputStream is = conn.getInputStream();
  10.  
  11.                BufferedInputStream bis = new BufferedInputStream(is);
  12.  
  13.                Bitmap bm = BitmapFactory.decodeStream(bis);
  14.  
  15.                bis.close();
  16.  
  17.                is.close();
  18.  
  19.                this.myImageView.setImageBitmap(bm);
  20.  
  21.           } catch (IOException e) {
  22.  
  23.                /* Reset to Default image on any error. */
  24.  
  25.                this.myImageView.setImageDrawable(getResources()
  26.  
  27.                          .getDrawable(R.drawable.default));
  28.  
  29.           }
  30.  
  31.      }
Parsed in 0.033 seconds, using GeSHi 1.0.8.4


Btw: I think these two lines are useless in your snippet, right :?::
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.                int[] bitmapData =new int[length];
  2.  
  3.                byte[] bitmapData2 =new byte[length];
Parsed in 0.034 seconds, using GeSHi 1.0.8.4


Best Regards,
plusminus
Image
Image | Android Development Community / Tutorials
User avatar
plusminus
Site Admin
Site Admin
 
Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

Postby raquibulbari » Sat Jan 26, 2008 1:43 pm

right man those two lines are not required at all

I missed it man, it would be great if i found your tutorial first, so much time waste i did
I am a pathetic looser :(
Shimugool
User avatar
raquibulbari
Developer
Developer
 
Posts: 25
Joined: Sun Dec 16, 2007 6:31 am
Location: dhaka,bangladesh

Postby Cheefrocker » Sat Feb 02, 2008 12:01 pm

Nice Tutorial!!

But how can i combinate your code with an gallery.

I want load many images and thow same in a gallery with an imageswitcher. can somebody help me?

thank you very much for your help!!
Cheefrocker
Freshman
Freshman
 
Posts: 4
Joined: Sat Feb 02, 2008 11:58 am

Postby plusminus » Sat Feb 02, 2008 12:50 pm

Hello Cheefrocker,

Created a tutorial for you and others: :src: Gallery with remote Images.

I hope you like it. :)

Regards,
plusminus
Image
Image | Android Development Community / Tutorials
User avatar
plusminus
Site Admin
Site Admin
 
Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

Bytes into inputstream

Postby zeeshan » Mon Mar 17, 2008 8:42 am

i have a bytes of image i want to convert into inputstream to show on listview ?? how can i do that
zeeshan
Experienced Developer
Experienced Developer
 
Posts: 68
Joined: Mon Mar 03, 2008 6:10 am

Top

problem with images from Google Charts

Postby GodsMoon » Tue Apr 08, 2008 3:18 am

I can get images from everywhere but Google Charts API http://code.google.com/apis/chart/

This doesn't work.
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. ImageView chart = (ImageView) findViewById(R.id.chart);
  2.  
  3.                 Bitmap bmImg;
  4.  
  5.                 try {
  6.  
  7.                                 URL chartUrl = new URL("http://chart.apis.google.com/chart?cht=lc&amp;chs=200x100&amp;chd=s:fohmnytenefohmnytene&amp;chxt=x,y&amp;chxl=0:|Apr|May|June|1:||50+Kb");
  8.  
  9.                                
  10.  
  11.                                 HttpURLConnection conn= (HttpURLConnection)chartUrl.openConnection();
  12.  
  13.                     conn.setDoInput(true);
  14.  
  15.                  
  16.  
  17.                     conn.connect();
  18.  
  19.                     int length = conn.getContentLength();
  20.  
  21.        
  22.  
  23.                     InputStream is = conn.getInputStream();
  24.  
  25.                    
  26.  
  27.                     bmImg = BitmapFactory.decodeStream(is);
  28.  
  29.                
  30.  
  31.                 chart.setImageBitmap(bmImg);
  32.  
  33.                
  34.  
  35.                 } catch (IOException e) {
  36.  
  37.                        /* Reset to Default image on any error. */
  38.  
  39.                        //this.myImageView.setImageDrawable(getResources().getDrawable(R.drawable.default));
  40.  
  41.                   }
Parsed in 0.038 seconds, using GeSHi 1.0.8.4

If I replace the google charts image everything works fine.
I get an "java.lang.IllegalArgumentException: Argument must not be null." from conn.connect();

I'm guessing its something funny with google charts, but I can't image what it is. The image work fine in the browser on Android.

Any ideas?
GodsMoon
Developer
Developer
 
Posts: 26
Joined: Mon Dec 10, 2007 5:13 pm

Postby GodsMoon » Tue Apr 08, 2008 4:26 am

Alright so I already figured this out. :D

If anyone is interested, you have to url encode the |
replace: http://chart.apis.google.com/chart?cht= ... ello|World
with: http://chart.apis.google.com/chart?cht= ... lo%7CWorld

and it works!
GodsMoon
Developer
Developer
 
Posts: 26
Joined: Mon Dec 10, 2007 5:13 pm

Postby dkkundudolan » Tue Apr 08, 2008 1:33 pm

Hi All,

this prog is alright. but during run, its showing "NullPointerException" . how to solve the probs?
please reply me soon.

thanks
dolan.
dkkundudolan
Experienced Developer
Experienced Developer
 
Posts: 83
Joined: Mon Mar 03, 2008 12:50 pm

Postby plusminus » Thu Apr 10, 2008 11:51 pm

dkkundudolan wrote:Hi All,

this prog is alright. but during run, its showing "NullPointerException" . how to solve the probs?
please reply me soon.

thanks
dolan.


:roll: where is it thrown :?:
Image
Image | Android Development Community / Tutorials
User avatar
plusminus
Site Admin
Site Admin
 
Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

Postby Jesmiatka » Tue Apr 15, 2008 12:07 pm

Hmm,

It seems I can't download images from HTTPS websites?
I get the I/O Exception thrown at conn.connect();

I already tried to make the openConnection a HttpsURLConnection but doesn't fix anything..
Opening the URL trough the browser (which I print in the log) works just fine!
Anyone knows how to download images from https?

Mike
Jesmiatka
Senior Developer
Senior Developer
 
Posts: 164
Joined: Mon Feb 04, 2008 3:37 pm
Location: Netherlands

Postby snowtiger » Wed Apr 23, 2008 10:40 am

Has anybody already tried to use GData webservices? Espacially PicasawebClient/Service?

I can't figure out, how to use this Picasa API. In a normal Java App it works fine, copy&paste the same code to an android project leads to a lot of errors. Its just the following code:

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. URL albumsUrl = new URL("http://picasaweb.google.com/data/feed/api/user/<usernameHere>?kind=album");
  2.  
  3.                 PicasawebService myService = new PicasawebService("exampleCo-exampleApp-1");
  4.  
  5.  
  6.  
  7.                 // Send the request for the user's albums.
  8.  
  9.                 UserFeed myUserFeed = myService.getFeed(albumsUrl, UserFeed.class);
  10.  
  11.  
  12.  
  13.                 // Print the title of the returned feed:
  14.  
  15.                 System.out.println(myUserFeed.getTitle().getPlainText());
Parsed in 0.037 seconds, using GeSHi 1.0.8.4


I already translated all the jars with retrotranslator for android, because google APIs won't work with google Android... WTF! But I still get an ExceptionInInitializerError. :(
snowtiger
Developer
Developer
 
Posts: 34
Joined: Fri Dec 21, 2007 10:44 am

Postby tdi » Mon Dec 29, 2008 12:57 am

dkkundudolan wrote:Hi All,

this prog is alright. but during run, its showing "NullPointerException" . how to solve the probs?
please reply me soon.

thanks
dolan.


Im getting the same exception....
12-29 00:54:56.539: ERROR/AndroidRuntime(197): Uncaught handler: thread main exiting due to uncaught exception
12-29 00:54:56.569: ERROR/AndroidRuntime(197): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.proadmin.stacjebenzynowe/com.proadmin.stacjebenzynowe.Stacjebenzynowe}: java.lang.NullPointerException
12-29 00:54:56.569: ERROR/AndroidRuntime(197): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2140)
12-29 00:54:56.569: ERROR/AndroidRuntime(197): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2156)
12-29 00:54:56.569: ERROR/AndroidRuntime(197): at android.app.ActivityThread.access$1800(ActivityThread.java:112)
12-29 00:54:56.569: ERROR/AndroidRuntime(197): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1580)
12-29 00:54:56.569: ERROR/AndroidRuntime(197): at android.os.Handler.dispatchMessage(Handler.java:88)
12-29 00:54:56.569: ERROR/AndroidRuntime(197): at android.os.Looper.loop(Looper.java:123)
12-29 00:54:56.569: ERROR/AndroidRuntime(197): at android.app.ActivityThread.main(ActivityThread.java:3742)
12-29 00:54:56.569: ERROR/AndroidRuntime(197): at java.lang.reflect.Method.invokeNative(Native Method)
12-29 00:54:56.569: ERROR/AndroidRuntime(197): at java.lang.reflect.Method.invoke(Method.java:515)
12-29 00:54:56.569: ERROR/AndroidRuntime(197): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
12-29 00:54:56.569: ERROR/AndroidRuntime(197): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:497)
12-29 00:54:56.569: ERROR/AndroidRuntime(197): at dalvik.system.NativeStart.main(Native Method)
12-29 00:54:56.569: ERROR/AndroidRuntime(197): Caused by: java.lang.NullPointerException
12-29 00:54:56.569: ERROR/AndroidRuntime(197): at com.proadmin.stacjebenzynowe.Stacjebenzynowe.onCreate(Stacjebenzynowe.java:29)
12-29 00:54:56.569: ERROR/AndroidRuntime(197): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1122)
12-29 00:54:56.569: ERROR/AndroidRuntime(197): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2103)
12-29 00:54:56.569: ERROR/AndroidRuntime(197): ... 11 more


the code is as follows ( XML is the same ):

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package com.proadmin.stacjebenzynowe;
  2.  
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.net.HttpURLConnection;
  6. import java.net.MalformedURLException;
  7. import java.net.URL;
  8.  
  9. import android.app.Activity;
  10. import android.graphics.Bitmap;
  11. import android.graphics.BitmapFactory;
  12. import android.os.Bundle;
  13. import android.util.Log;
  14. import android.view.View;
  15. import android.widget.Button;
  16. import android.widget.ImageView;
  17.  
  18. public class Stacjebenzynowe extends Activity {
  19.     /** Called when the activity is first created. */
  20.        
  21.         ImageView imView;
  22.         String imageUrl = "http://seth.coloco.pl/~tdi/";
  23.        
  24.     @Override
  25.     public void onCreate(Bundle icicle) {
  26.         super.onCreate(icicle);
  27.         setContentView(R.layout.main);
  28.         Button bt = (Button) findViewById(R.id.get_imagebt);
  29.         bt.setOnClickListener( new View.OnClickListener() {    
  30.                 public void onClick(View view) {
  31.                         downloadFile(imageUrl+"stacje.jpg");
  32.                 }
  33.         });
  34.         imView = (ImageView) findViewById(R.id.imview);
  35.         Log.i("im url",imageUrl+"png.png");
  36.     }
  37.     private Bitmap bmImg;
  38.     void downloadFile(String fileUrl) {
  39.         //URL myFileUrl = null;
  40. //      try {
  41. //              myFileUrl = new URL     (fileUrl);
  42. //      } catch (MalformedURLException e) {
  43. //              Log.d("stacje",e.toString());
  44. //      }
  45. //      try {
  46. //              HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
  47. //             
  48. //              conn.connect();
  49. //             
  50. //              InputStream is = conn.getInputStream();
  51. //              bmImg = BitmapFactory.decodeStream(is);
  52. //              is.close();
  53. //             
  54. //              this.imView.setImageBitmap(bmImg);
  55. //      this.imView.setScaleType(ImageView.ScaleType.FIT_CENTER);
  56. //      } catch (IOException e ){
  57. //              Log.d("stacje",e.toString());
  58. //      }
  59.     }
  60.    
  61.    
  62. }
  63.  
Parsed in 0.045 seconds, using GeSHi 1.0.8.4
---
Dariusz Dwornikowski
My CS site
User avatar
tdi
Freshman
Freshman
 
Posts: 7
Joined: Wed Dec 24, 2008 2:17 pm
Location: Poland

Postby tdi » Mon Dec 29, 2008 8:50 am

ok i found what the problem was. In XML file, instead of having <Button id="...., i had to have <Button android:id="....

Image does not get downloaded because of SocketException but that i will try to handle

edit:
I added :
Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
  1.  
  2. <uses-permission android:name="android.permission.INTERNET"></uses-permission>
Parsed in 0.000 seconds, using GeSHi 1.0.8.4

and works.

Thanks for great tutorials.
---
Dariusz Dwornikowski
My CS site
User avatar
tdi
Freshman
Freshman
 
Posts: 7
Joined: Wed Dec 24, 2008 2:17 pm
Location: Poland

Postby androidrocks » Thu Apr 02, 2009 4:01 pm

string url1 = "my url";
URL url = new URL(url1);
URLConnection conn = url.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
BitmapFactory.Options bf = new BitmapFactory.Options();
bm = BitmapFactory.decodeStream(bis);
imgView.setImageBitmap(bm);

I am using this code to get the image from web and set it on imageview . But the issue is the width that i get is the same as original image. I want to increase the width of the image so that it automatically fits as per the screen size. Any idea on how to increase the width of the bitmap image.

When I use drawable it automatically fits the same image as the screen size. I use drawable.setBackground(drawableimage);

But this is not the case with bitmap image. Any idea on how to increase the width of the bitmap image.
androidrocks
Freshman
Freshman
 
Posts: 6
Joined: Tue Mar 24, 2009 8:47 am

Top
Next

Return to Novice Tutorials

Who is online

Users browsing this forum: No registered users and 4 guests