Android- inserting external image from URL to placeholder in the app - android

Pretty new to Android development, haven't found the answer needed.
I have an ImageView some layout.xml:
<ImageView
android:layout_width="48dp"
android:layout_height="48dp"
android:src="#drawable/placeholder"
android:layout_alignParentRight="true" />
Instead the placeholder, I want to load some specific image from url that i have.
How can it be achieved?

for download the image for url ,first download that image and saved it in Bitmap
public static Bitmap loadBitmap(String url) {
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(url).openStream(),IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 1;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
} catch (IOException e) {
Log.e(TAG, "Could not load Bitmap from: " + url);
} finally {
closeStream(in);
closeStream(out);
}
return bitmap;
Than you can set image by call that method
image.setImageBitmap(bitmap);
Hope it will help you

Use Picasso Library for android to download images from url and display onto ImageView
Its very easy to use like this
Picasso.with(context).load("http://your_image_url").into(your_imageView);

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
And call from your onCreate() method using:
new DownloadImageTask((ImageView) findViewById(R.id.imageView1))
.execute(MY_URL_STRING);
Dont forget to add below permission in your manifest file
<uses-permission android:name="android.permission.INTERNET"/>

you may try ImageLoader,you can download it here https://github.com/nostra13/Android-Universal-Image-Loader

Related

load image from URL and save on memory in android

How to load image from URL and save that on memory of device in android? Dont say me use Picasso or oser laibrary.
I need to:
If device get internet conection I load image to ImageView from url and save it on memory of device, else I need to load one of save image to imageView. Thank`s for helps
P.S. Sorry me, I can make some mistakes in question because I don`t very good know English.
This my class:
public class ImageManager {
String file_path;
Bitmap bitmap = null;
public Bitmap donwoaledImageFromSD() {
File image = new File(Environment.getExternalStorageDirectory().getPath(),file_path);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(),bmOptions);
return bitmap;
}
private void savebitmap() {
File file = new File("first");
file_path = file.getAbsolutePath();
try {
FileOutputStream fileOutputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90,fileOutputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
public void fetchImage(final String url, final ImageView iView) {
new AsyncTask<String, Void, Bitmap>() {
protected Bitmap doInBackground(String... iUrl) {
try {
InputStream in = new URL(url).openStream();
bitmap = BitmapFactory.decodeStream(in);
savebitmap();
} catch (Exception e) {
donwoaledImageFromSD();
}
return bitmap;
}
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if (iView != null) {
iView.setImageBitmap(result);
}
}
}.execute(url);
}
}
Try to use this code:
Method for loading image from imageUrl
public Bitmap getBitmapFromURL(String imageUrl) {
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection)
url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
Bitmap imageBitmap = BitmapFactory.decodeStream(inputStream);
return imageBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
And You should use it in a separate thread, like that:
new Thread(new Runnable() {
#Override
public void run() {
try {
Bitmap bitmap = getBitmapFromURL(<URL of your image>);
imageView.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
e.getMessage();
}
}
}).start();
But using Picasso - indeed a better way.
Update:
For saving Bitmap to file on external storage (SD card) You can use method like this:
public static void writeBitmapToSD(String aFileName, Bitmap aBitmap) {
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
return;
}
File sdPath = Environment.getExternalStorageDirectory();
File sdFile = new File(sdPath, aFileName);
if (sdFile.exists()) {
sdFile.delete ();
}
try {
FileOutputStream out = new FileOutputStream(sdFile);
aBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
}
}
Remember that You need
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
for it.
And for loading `Bitmap` from file on external storage You can use method like that:
public static Bitmap loadImageFromSD(String aFileName) {
Bitmap result = null;
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
try {
FileInputStream fis = new FileInputStream(new File(Environment.getExternalStorageDirectory(), aFileName));
result = BitmapFactory.decodeStream(fis);
fis.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "loadImageFromSD: " + e.getMessage());
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
You need
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
to do this.
Update 2
Method getBitmapFromURL(), but ImageView should be updated from UI thread, so You should call getBitmapFromURL(), for example, this way:
new Thread(new Runnable() {
#Override
public void run() {
try {
final Bitmap bitmap = getBitmapFromURL("<your_image_URL>");
runOnUiThread(new Runnable() {
#Override
public void run() {
imageView.setImageBitmap(bitmap);
}
});
} catch (Exception e) {
e.printStackTrace();
e.getMessage();
}
}
}).start();
I had this same issue and I hope this helps. First, To download Image from URL into your app, use the code below:
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
In order for the image to be displayed inside the app, use the method below in your onCreate method:
new DownloadImageTask((ImageView) -your imageview id-)
.execute(-your URL-);
In order for the image to be saved INTERNALLY inside the app/phone, use the code below:
#SuppressLint("WrongThread")
protected void onPostExecute(Bitmap result) {
if (result != null) {
File dir = new File(peekAvailableContext().getFilesDir(), "MyImages");
if(!dir.exists()){
dir.mkdir();
}
File destination = new File(dir, "image.jpg");
try {
destination.createNewFile();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
result.compress(Bitmap.CompressFormat.PNG, 0, bos);
byte[] bitmapdata = bos.toByteArray();
FileOutputStream fos = new FileOutputStream(destination);
fos.write(bitmapdata);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
bmImage.setImageBitmap(result);
}
}
To load the image from the internal storage, use the code below:
private void loadImageFromStorage(String path)
{
try {
File f=new File(path, "image.jpg");
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
ImageView img=(ImageView)findViewById(R.id.businessCard_iv);
img.setImageBitmap(b);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
Things to note: 1. path is the a string containing the path of the file. 2. "image.jpg" is the file name so ensure that matches with yours. 3. "MyImages" is a folder in your path which contains the actual saved image.

Load image larger than 2048x2048 into ImageView on Android

I need to load high res remote images to imageview, but without using any external libraries or frameworks. Images are like 2150x1500 px, and here is my code for loading:
URL imageUrl = new URL(url);
HttpURLConnection connection;
if (url.startsWith("https://")) {
connection = (HttpURLConnection) imageUrl.openConnection();
} else {
connection = (HttpURLConnection) imageUrl.openConnection();
}
connection.setConnectTimeout(30000);
connection.setReadTimeout(30000);
connection.setInstanceFollowRedirects(true);
InputStream is = connection.getInputStream();
OutputStream os = new FileOutputStream(f);
CacheUtils.CopyStream(is, os);
os.close();
image = decodeFile(f);
img.setImageBitmap(image);
and here is decodeFile function:
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
and I always get texture size too big exception. Is there any way to load these images? Or is there a way to resize image not 2 or 4 times, but resize to fit 2048 pixels by width?
class DownloadImage extends AsyncTask<String, Void, Bitmap>
{
ImageView bmImage;
public DownloadImage(ImageView bmImage) {
this.bmImage = bmImage;
}
#Override
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
#Override
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(Bitmap.createScaledBitmap(result, 120, 120, false));
}
}
Specify the height and width you need instead of 120.
Call this in your oncreate
new DownloadImage((ImageView) findViewById(R.id.imageView1))
.execute("https://.........");

JSON to retrieve image

I am using JSON to retrieve user data and I am also getting the image URL but how can I show the image instead of the URL? Currently it only shows the URL from the image.
Here is the code:
StringBuilder tweetResultBuilder = new StringBuilder();
try {
//get JSONObject from result
JSONObject resultObject = new JSONObject(result);
//get JSONArray contained within the JSONObject retrieved - "results"
JSONArray tweetArray = resultObject.getJSONArray("results");
//loop through each item in the tweet array
for (int t=0; t<tweetArray.length(); t++) {
//each item is a JSONObject
JSONObject tweetObject = tweetArray.getJSONObject(t);
//get the username and text content for each tweet
tweetResultBuilder.append(tweetObject.getString("from_user")+": ");
tweetResultBuilder.append(tweetObject.get("profile_image_url")+"\n");
tweetResultBuilder.append(tweetObject.get("text")+"\n\n");
}
}
You should download and cashe you image first.
Please read this article Displaying Bitmaps Efficiently, and check Sample application
The shorter way to display image from url:
new DownloadImageTask((ImageView) findViewById(R.id.imageView1))
.execute("http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png");
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
You need to download image from the url you are getting.
For that you need to do following things.
ImageView my_image = (ImageView) findViewById(R.id.my_imageView);
String image_url = "http://www.clker.com/cliparts/1/d/7/e/12570918991185627521Ramiras_Earth_small_icon.svg.med.png";
Bitmap bm = getImageFromServer(image_url);
my_image.setImageBitmap(bm);
This will call the following function to download image.
private Bitmap getImageFromServer(String image_url) {
Bitmap bm = null;
try {
URL aURL = new URL(image_url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e("DEBUGTAG", "Remtoe Image Exception", e);
}
return bm;
}
That's it. Hope this helps you somehow.
Thanks.
try this one
try {
ImageView i = (ImageView)findViewById(R.id.image);
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageUrl).getContent());
i.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

Android - How can I display an image from a URL?

I have an ImageView and all I need to do is display an image from the intetrnet when the app loads. Is there a very simple way to do this?
ImageView.setImageURI does not seem to work for internet resources, so you should read the bitmap yourself.
InputStream is = new URL("http://example.com/myimage.jpg").openStream();
Bitmap bitmap = BitmapFactory.decodeStream(is);
is.close();
ImageView iv = (ImageView) findViewById(R.id.myImage);
iv.setImageBitmap(bitmap);
But this loads the image on the UI thread, which can cause hiccups. It is preferable to do it in a different thread, for example using:
new AsyncTask<String, Void, Bitmap>() {
protected Bitmap doInBackground(String... params) {
try {
return loadBitmap(params[0]);
} catch (Exception e) {
Log.e("imagetask", "error loading bitmap", e);
return null;
}
}
protected Bitmap loadBitmap(String urlSpec) throws IOException {
InputStream is = new URL(urlSpec).openStream();
try {
return BitmapFactory.decodeStream(is);
} finally {
is.close();
}
}
protected void onPostExecute(Bitmap bitmap) {
if (bitmap != null) {
ImageView iv = (ImageView) findViewById(R.id.myImage);
iv.setImageBitmap(bitmap);
}
}
}.execute("http://example.com/myimage.jpg");
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet( url);
HttpResponse response = client.execute( get );
Bitmap bitmap = BitmapFactory.decodeStream( response.getEntity().getContent() );

How to load an ImageView by URL in Android?

How do you use an image referenced by URL in an ImageView?
From Android developer:
// show The Image in a ImageView
new DownloadImageTask((ImageView) findViewById(R.id.imageView1))
.execute("http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png");
public void onClick(View v) {
startActivity(new Intent(this, IndexActivity.class));
finish();
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
Make sure you have the following permissions set in your AndroidManifest.xml to access the internet.
<uses-permission android:name="android.permission.INTERNET" />
1. Picasso allows for hassle-free image loading in your application—often in one line of code!
Use Gradle:
implementation 'com.squareup.picasso:picasso:(insert latest version)'
Just one line of code!
Picasso.get().load("http://i.imgur.com/DvpvklR.png").into(imageView);
2. Glide An image loading and caching library for Android focused on smooth scrolling
Use Gradle:
repositories {
mavenCentral()
google()
}
dependencies {
implementation 'com.github.bumptech.glide:glide:4.11.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
}
// For a simple view:
Glide.with(this).load("http://i.imgur.com/DvpvklR.png").into(imageView);
3. fresco is a powerful system for displaying images on Android applications. Fresco takes care of image loading and display, so you don't have to.
Getting Started with Fresco
You'll have to download the image firstly
public static Bitmap loadBitmap(String url) {
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 1;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
} catch (IOException e) {
Log.e(TAG, "Could not load Bitmap from: " + url);
} finally {
closeStream(in);
closeStream(out);
}
return bitmap;
}
Then use the Imageview.setImageBitmap to set bitmap into the ImageView
Anyway people ask my comment to post it as answer. i am posting.
URL newurl = new URL(photo_url_str);
mIcon_val = BitmapFactory.decodeStream(newurl.openConnection().getInputStream());
profile_photo.setImageBitmap(mIcon_val);
I wrote a class to handle this, as it seems to be a recurring need in my various projects:
https://github.com/koush/UrlImageViewHelper
UrlImageViewHelper will fill an
ImageView with an image that is found
at a URL.
The sample will do a Google Image
Search and load/show the results
asynchronously.
UrlImageViewHelper will automatically
download, save, and cache all the
image urls the BitmapDrawables.
Duplicate urls will not be loaded into
memory twice. Bitmap memory is managed
by using a weak reference hash table,
so as soon as the image is no longer
used by you, it will be garbage
collected automatically.
The accepted answer above is great if you are loading the image based on a button click, however if you are doing it in a new activity it freezes up the UI for a second or two. Looking around I found that a simple asynctask eliminated this problem.
To use an asynctask add this class at the end of your activity:
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
And call from your onCreate() method using:
new DownloadImageTask((ImageView) findViewById(R.id.imageView1))
.execute(MY_URL_STRING);
The result is a quickly loaded activity and an imageview that shows up a split second later depending on the user's network speed.
You could also use this LoadingImageView view to load an image from a url:
http://blog.blundellapps.com/imageview-with-loading-spinner/
Once you have added the class file from that link you can instantiate a url image view:
in xml:
<com.blundell.tut.LoaderImageView
android:id="#+id/loaderImageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
image="http://developer.android.com/images/dialog_buttons.png"
/>
In code:
final LoaderImageView image = new LoaderImageView(this, "http://developer.android.com/images/dialog_buttons.png");
And update it using:
image.setImageDrawable("http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png");
The best modern library for such a task in my opinion is Picasso by Square. It allows to load an image to an ImageView by URL with one-liner:
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
public class LoadWebImg extends Activity {
String image_URL=
"http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView bmImage = (ImageView)findViewById(R.id.image);
BitmapFactory.Options bmOptions;
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
Bitmap bm = LoadImage(image_URL, bmOptions);
bmImage.setImageBitmap(bm);
}
private Bitmap LoadImage(String URL, BitmapFactory.Options options)
{
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in, null, options);
in.close();
} catch (IOException e1) {
}
return bitmap;
}
private InputStream OpenHttpConnection(String strURL) throws IOException{
InputStream inputStream = null;
URL url = new URL(strURL);
URLConnection conn = url.openConnection();
try{
HttpURLConnection httpConn = (HttpURLConnection)conn;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
}
catch (Exception ex)
{
}
return inputStream;
}
}
Hi I have the most easiest code try this
public class ImageFromUrlExample extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView imgView =(ImageView)findViewById(R.id.ImageView01);
Drawable drawable = LoadImageFromWebOperations("http://www.androidpeople.com/wp-content/uploads/2010/03/android.png");
imgView.setImageDrawable(drawable);
}
private Drawable LoadImageFromWebOperations(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;
}
}
}
main.xml
<LinearLayout
android:id="#+id/LinearLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
android:id="#+id/ImageView01"
android:layout_height="wrap_content"
android:layout_width="wrap_content"/>
try this
I have recently found a thread here, as I have to do a similar thing for a listview with images, but the principle is simple, as you can read in the first sample class shown there (by jleedev).
You get the Input stream of the image (from web)
private InputStream fetch(String urlString) throws MalformedURLException, IOException {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(urlString);
HttpResponse response = httpClient.execute(request);
return response.getEntity().getContent();
}
Then you store the image as Drawable and you can pass it to the ImageView (via setImageDrawable). Again from the upper code snippet take a look at the entire thread.
InputStream is = fetch(urlString);
Drawable drawable = Drawable.createFromStream(is, "src");
Lots of good info in here...I recently found a class called SmartImageView that seems to be working really well so far. Very easy to incorporate and use.
http://loopj.com/android-smart-image-view/
https://github.com/loopj/android-smart-image-view
UPDATE: I ended up writing a blog post about this, so check it out for help on using SmartImageView.
2ND UPDATE: I now always use Picasso for this (see above) and highly recommend it. :)
This is a late reply, as suggested above AsyncTask will will and after googling a bit i found one more way for this problem.
Drawable drawable = Drawable.createFromStream((InputStream) new URL("url").getContent(), "src");
imageView.setImageDrawable(drawable);
Here is the complete function:
public void loadMapPreview () {
//start a background thread for networking
new Thread(new Runnable() {
public void run(){
try {
//download the drawable
final Drawable drawable = Drawable.createFromStream((InputStream) new URL("url").getContent(), "src");
//edit the view in the UI thread
imageView.post(new Runnable() {
public void run() {
imageView.setImageDrawable(drawable);
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
Don't forget to add the following permissions in your AndroidManifest.xml to access the internet.
<uses-permission android:name="android.permission.INTERNET" />
I tried this myself and i have not face any issue yet.
imageView.setImageBitmap(BitmapFactory.decodeStream(imageUrl.openStream()));//try/catch IOException and MalformedURLException outside
This will help you...
Define imageview and load image into it .....
Imageview i = (ImageView) vv.findViewById(R.id.img_country);
i.setImageBitmap(DownloadFullFromUrl(url));
Then Define this method :
public Bitmap DownloadFullFromUrl(String imageFullURL) {
Bitmap bm = null;
try {
URL url = new URL(imageFullURL);
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
bm = BitmapFactory.decodeByteArray(baf.toByteArray(), 0,
baf.toByteArray().length);
} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
return bm;
}
String img_url= //url of the image
URL url=new URL(img_url);
Bitmap bmp;
bmp=BitmapFactory.decodeStream(url.openConnection().getInputStream());
ImageView iv=(ImageView)findviewById(R.id.imageview);
iv.setImageBitmap(bmp);
Version with exception handling and async task:
AsyncTask<URL, Void, Boolean> asyncTask = new AsyncTask<URL, Void, Boolean>() {
public Bitmap mIcon_val;
public IOException error;
#Override
protected Boolean doInBackground(URL... params) {
try {
mIcon_val = BitmapFactory.decodeStream(params[0].openConnection().getInputStream());
} catch (IOException e) {
this.error = e;
return false;
}
return true;
}
#Override
protected void onPostExecute(Boolean success) {
super.onPostExecute(success);
if (success) {
image.setImageBitmap(mIcon_val);
} else {
image.setImageBitmap(defaultImage);
}
}
};
try {
URL url = new URL(url);
asyncTask.execute(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
private Bitmap getImageBitmap(String url) {
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e(TAG, "Error getting bitmap", e);
}
return bm;
}
A simple and clean way to do this is to use the open source library Prime.
This code is tested, it is completely working.
URL req = new URL(
"http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png"
);
Bitmap mIcon_val = BitmapFactory.decodeStream(req.openConnection()
.getInputStream());
Working for imageView in any container , like listview grid view , normal layout
private class LoadImagefromUrl extends AsyncTask< Object, Void, Bitmap > {
ImageView ivPreview = null;
#Override
protected Bitmap doInBackground( Object... params ) {
this.ivPreview = (ImageView) params[0];
String url = (String) params[1];
System.out.println(url);
return loadBitmap( url );
}
#Override
protected void onPostExecute( Bitmap result ) {
super.onPostExecute( result );
ivPreview.setImageBitmap( result );
}
}
public Bitmap loadBitmap( String url ) {
URL newurl = null;
Bitmap bitmap = null;
try {
newurl = new URL( url );
bitmap = BitmapFactory.decodeStream( newurl.openConnection( ).getInputStream( ) );
} catch ( MalformedURLException e ) {
e.printStackTrace( );
} catch ( IOException e ) {
e.printStackTrace( );
}
return bitmap;
}
/** Usage **/
new LoadImagefromUrl( ).execute( imageView, url );
Try this way,hope this will help you to solve your problem.
Here I explain about how to use "AndroidQuery" external library for load image from url/server in asyncTask manner with also cache loaded image to device file or cache area.
Download "AndroidQuery" library from here
Copy/Paste this jar to project lib folder and add this library to project build-path
Now I show demo to how to use it.
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/imageFromUrl"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"/>
<ProgressBar
android:id="#+id/pbrLoadImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"/>
</FrameLayout>
</LinearLayout>
MainActivity.java
public class MainActivity extends Activity {
private AQuery aQuery;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
aQuery = new AQuery(this);
aQuery.id(R.id.imageFromUrl).progress(R.id.pbrLoadImage).image("http://itechthereforeiam.com/wp-content/uploads/2013/11/android-gone-packing.jpg",true,true);
}
}
Note : Here I just implemented common method to load image from url/server but you can use various types of method which can be provided by "AndroidQuery"to load your image easily.
Android Query can handle that for you and much more (like cache and loading progress).
Take a look at here.
I think is the best approach.

Categories

Resources