Android : Load image from web URL [duplicate] - android

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Loading remote images
I am developing an application where I have a list in which each row has an image,
this image is loaded from a web URL.
below is my code
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/list_row_img"
android:layout_width="200dp"
android:layout_height="200dp"
/>
<TextView
android:id="#+id/list_row_description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
and this is the activity code
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView img= (ImageView) findViewById(R.id.list_row_img);
Bitmap bm = null;
try {
URL aURL = new URL("http://image10.bizrate-images.com/resize?sq=60&uid=2216744464");
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
img.setImageBitmap(bm);
bis.close();
is.close();
} catch (Exception e) {
Log.v("EXCEPTION", "Error getting bitmap", e);
}
}
when I run i get nothing on the device. only a gray screen and no exception happens.
note that i added this permission in the manifest file
<uses-permission android:name="android.permission.INTERNET" />
can anyone help me please ?

try this
you can exeecute it by
new DownloadImageTask((ImageView) im1).execute(url here);
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;
}
/* #Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
showProgressDialog();
}*/
protected void onPostExecute(Bitmap result) {
//pDlg.dismiss();
bmImage.setImageBitmap(result);
}}

Use below code for download image from url and display image into imageview, this will solve your problem.
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
public class MainActivity extends Activity {
ImageView mImgView1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
mImgView1 = (ImageView) findViewById(R.id.mImgView1);
String url = "https://www.morroccomethod.com/components/com_virtuemart/shop_image/category/resized/Trial_Sizes_4e4ac3b0d3491_175x175.jpg";
BitmapFactory.Options bmOptions;
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
Bitmap bm = loadBitmap(url, bmOptions);
mImgView1.setImageBitmap(bm);
}
public static Bitmap loadBitmap(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 static 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;
}
}

The link for your image is invalid. Try to access it with your browser, you will find out. thats your problem.

Related

Downloading image from server using Android

I am trying to download an image from the internet. Right now the app downloads only part of the image, but then it stops. I am using AsyncTask. Any suggestions on what to do?
The error I get is:
android.os.NetworkOnMainThreadException
at com.example.reynaldo.getimageserver.MainActivity$DownloadAsyncTask.onPostExecute(MainActivity.java:74)
W/System.err: at com.example.reynaldo.getimageserver.MainActivity$DownloadAsyncTask.onPostExecute(MainActivity.java:30)
This is the code I have:
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick (View view){
DownloadAsyncTask task = new DownloadAsyncTask();
task.execute(new String[] {"http://res.cloudinary.com/demo/image/upload/w_500,f_auto/sample.jpg" });
}
private class DownloadAsyncTask extends AsyncTask<String, Void, String> {
Bitmap bitmap = null;
InputStream in = null;
#Override
protected String doInBackground(String... urls){
int response = -1;
URL url;
try {
url = new URL("http://res.cloudinary.com/demo/image/upload/w_500,f_auto/sample.jpg");
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
System.out.println("This is wrong");
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
return "success";
}
}
catch (IOException e) {
System.out.println("IOException");
}
return "Download failed";
}
#Override
protected void onPostExecute(String result) {
//try {
bitmap = BitmapFactory.decodeStream(in);
/* in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}*/
ImageView img = (ImageView) findViewById(R.id.image);
img.setImageBitmap(bitmap);
}
}
}
try this if you dont want to use third party library
new DownloadImage(Imageview).execute(YourUrl);
Create a AsyncTask Class
public class DownloadImage extends AsyncTask<String, Void, Bitmap> {
CircleImageView bmImage;
public DownloadImage(ImageView bmImage) {
this.bmImage = (CircleImageView) 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.d("Error", e.getStackTrace().toString());
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}

Titanium android remote image not shown

I am using Titanium to build a cross-platform mobile application, which I mostly tested with the iOS simulator and where I already got all functionality working. Now I want to have the app also bugfree on Android. One of the issues I'm facing right now is that the remote images are not shown anymore (while they were on iOS). The url from the remote images can is retrieved from the server and should be correct, as I see the images on iOS. This is one of the image urls:
http://elgg.masaer.com/mod/profile/icondirect.php?joindate=1426024336&guid=47&size=large
This is the code I use to show the image:
var profilePic = Titanium.UI.createImageView({
image: post.User.avatar,
width: '60px',
height: '60px',
borderRadius: 5
});
Does anybody know what could be the issue. Maybe it is because the url doesn't really have an extension of the image file? Thanks in advance!
possible answer is this
import java.net.URLConnection;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
public class MainActivity extends Activity {
ImageView mImgView1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
mImgView1 = (ImageView) findViewById(R.id.mImgView1);
String url = "https://www.morroccomethod.com/components/com_virtuemart/shop_image/category/resized/Trial_Sizes_4e4ac3b0d3491_175x175.jpg";
BitmapFactory.Options bmOptions;
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
Bitmap bm = loadBitmap(url, bmOptions);
mImgView1.setImageBitmap(bm);
}
public static Bitmap loadBitmap(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 static 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;
}
}
After some searching I found out that android is not smart enough to work with image urls and you have to retrieve the imagedata yourself. This can be used to download the remote image.
function loadImage(imageView,url) {
var http = Titanium.Network.createHTTPClient();
http.onload = function() {
imageView.image=this.responseData;
};
http.open('GET',url);
http.send();
};

with android set wallpaper from url i dont understand

Hi everyone I've check the post on the set wallpaper from URL but I am really new to programing and I still do not undertand it, could someone provide me with an example, basically I have an image on a server and I want to push a button and set it as the phone wallpaper thank you again for the help
public class TestingThree extends Activity {
ImageView image;
private class BackgroundTask extends AsyncTask
<String, Void, Bitmap> {
protected Bitmap doInBackground(String...url) {
//--- download an image ---
Bitmap bitmap = DownloadImage(url[0]);
return bitmap;
}
protected void onPostExecute(Bitmap bitmap) {
ImageView image = (ImageView) findViewById(R.id.imageView1);
image.setImageBitmap(bitmap);
}
}
private InputStream OpenHttpConnection(String urlString)
throws IOException
{InputStream in = null;
int response= -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection ))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK){
in = httpConn.getInputStream();
}
}
catch (Exception ex)
{
throw new IOException("Error connecting");
}
return in;
}
private Bitmap DownloadImage(String URL)
{
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
}
catch (IOException e1){
Toast.makeText(this,e1.getLocalizedMessage(),
Toast.LENGTH_LONG).show();
e1.printStackTrace();
}
return bitmap;
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.wallpaper);
new BackgroundTask().execute("http://myglobaljournal.com/images/imagetest.jpg");
Button setWallpaper = (Button) findViewById(R.id.button3);
setWallpaper.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
WallpaperManager wManager;
Bitmap bitmap;
try {
bitmap = BitmapFactory.decodeFile(null);
wManager = WallpaperManager.getInstance(getApplicationContext());
wManager.setBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
am trying to implement it to the button at the bottom where i pull the image from the link and set it directly as a wallpaper
thank you again
try this:
ImageView image;
private class BackgroundTask extends AsyncTask
<String, Void, Bitmap> {
protected Bitmap doInBackground(String...url) {
//--- download an image ---
Bitmap bitmap = DownloadImage(url[0]);
return bitmap;
}
protected void onPostExecute(Bitmap bitmap) {
ImageView image = (ImageView) findViewById(R.id.imageView1);
bitmaptwo=bitmap;
image.setImageBitmap(bitmap);
}
}
private InputStream OpenHttpConnection(String urlString)
throws IOException
{InputStream in = null;
int response= -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection ))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK){
in = httpConn.getInputStream();
}
}
catch (Exception ex)
{
throw new IOException("Error connecting");
}
return in;
}
private Bitmap DownloadImage(String URL)
{
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
}
catch (IOException e1){
Toast.makeText(this,e1.getLocalizedMessage(),
Toast.LENGTH_LONG).show();
e1.printStackTrace();
}
return bitmap;
}
public Bitmap bitmaptwo;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.wallpaper);
new BackgroundTask().execute("http://myglobaljournal.com/images/imagetest.jpg");
Button setWallpaper = (Button) findViewById(R.id.button3);
setWallpaper.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
WallpaperManager wManager;
try {
// bitmap = BitmapFactory.decodeFile(null);
wManager = WallpaperManager.getInstance(getApplicationContext());
wManager.setBitmap(bitmaptwo);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
Required Permission:
<uses-permission android:name="android.permission.SET_WALLPAPER"/>

Android load an image from url on button click

I want to load an image from url on a button click & to show it on activity imageview.
how to do it?
I try the following code but it shows the system error like java.net.UnknownHostException Host is on resolved.
package com.v3.thread.fetchImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.http.HttpException;
import org.apache.http.conn.HttpHostConnectException;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainThreadActivity extends Activity {
ImageView img_downloaded;
Button btn_download;
String fileurl = "http://variable3.com/files/images/email-sig.jpg";
Bitmap bmImg;
private ProgressDialog dialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//new MainThreadActivity().onPreExecute();
img_downloaded = (ImageView) findViewById(R.id.imageView1);
btn_download = (Button) findViewById(R.id.btnLoad);
btn_download.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
try {
downloadfile(fileurl);
} catch (HttpHostConnectException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public void AbstractProgressTask() {
dialog = new ProgressDialog(this);
}
protected void onPreExecute() {new MainThreadActivity().onPreExecute();
this.dialog.setMessage("Loading. Please wait...");
this.dialog.show();
}
/**
* method is called after the work is done.
*
* #param success result of #doInBackground method.
*/
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
// automatically done on worker thread (separate from UI thread)
protected Boolean doInBackground(final String... args) {
// here is your code
return true;
}
void downloadfile(String fileurl) throws HttpException,HttpHostConnectException {
URL myFileUrl = null;
try {
myFileUrl = new URL(fileurl);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
int length = conn.getContentLength();
if(length>0)
{
int[] bitmapData =new int[length];
byte[] bitmapData2 =new byte[length];
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
//img.setImageBitmap(bmImg);
}
else
{
int[] bitmapData =new int[length];
byte[] bitmapData2 =new byte[length];
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
}
}
catch(IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
please tell me where i hav to change
That seems like a lot of code just to show on an ImageView. Try this instead:
URL url = new URL("http://variable3.com/files/images/email-sig.jpg");
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
img_downloaded.setImageBitmap(bmp);
Use the following code for that, it will help you
Drawable drawable = LoadImageFromWebOperations(backImgUrl);
bagImgBtn.setBackgroundDrawable(drawable);
private Drawable LoadImageFromWebOperations(String url) {
// TODO Auto-generated method stub
try
{
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
}catch (Exception e) {
if (LogD) {
Log.d(TAG, e.toString());
e.printStackTrace();
}
return null;
}
}
Create a new onClick method called downloadButton.
public void downloadButton(View view){
Log.i("Button Status", "Button Pressed");
downloadImage imagedownload = new downloadImage();
Bitmap image;
try {
image = imagedownload.execute("Paste URL address of an image").get();
imageView.setImageBitmap(image);
}catch (Exception e){
e.printStackTrace();
}
}
Create a class called downloadImage which extends AysncTask.
public class downloadImage extends AsyncTask<String, Void, Bitmap>{
#Override
protected Bitmap doInBackground(String... urls) {
try {
URL url = new URL(urls[0]);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
InputStream inputStream = httpURLConnection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
}
Just call the following method on Button Click:
Drawable drawable_from_url(String url, String src_name) throws java.net.MalformedURLException, java.io.IOException
{
return Drawable.createFromStream(((java.io.InputStream)new java.net.URL(url).getContent()), src_name);
}
where url is the url to pass and src_name is any String(say "src")
Hope this will help you
I want to load an image from url on a button click & to show it on activity imageview
You have to do something like below within onPageFinished:
public void onPageFinished (WebView view, String url) {
wv.loadUrl(javascript);
view.getSettings().setLoadsImagesAutomatically(true);
wv.setVisibility(View.VISIBLE);
}

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