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
I want to get the photo from internet so I use setImageURI, but it seems can't be done, but if I use setImageResource(R.drawable.) under the same function, it works... How could I fix the setImageURI's error?
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);
//this is working
int p = R.drawable.fb;
i.setImageResource(p);
//this is not working
i.setImageURI(Uri.parse("http://www.vaultads.com/wp-content/uploads/2011/03/google-adsense.jpg"));
return i;
}
wan to get the photo from internet so i use setImageURI, but it seems
cant be done, but while if i use setImageResource(R.drawable.)
The most most important thing
setImageResource is synchronous so it will execute correctly but setImageURI from URL is asynchronous operation and it must be performed in separate thread than UI thread
Following Snippet will help you.
new Thread() {
public void run() {
try {
url = new URL("http://www.vaultads.com/wp-content/uploads/2011/03/google-adsense.jpg");
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
image = BitmapFactory.decodeStream(url.openStream());
} catch (IOException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
i.setImageBitmap(image);
}
});
}
}.start();
In case that too don't work then You have three other options
Option1
URL myUrl = new URL("http://www.vaultads.com/wp-content/uploads/2011/03/google-adsense.jpg");
InputStream inputStream = (InputStream)myUrl.getContent();
Drawable drawable = Drawable.createFromStream(inputStream, null);
i.setImageDrawable(drawable);
Option2
try {
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL("http://www.vaultads.com/wp-content/uploads/2011/03/google-adsense.jpg").getContent());
i.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Option3
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;
}
i.setImageBitmap(loadBitmap("http://www.vaultads.com/wp-content/uploads/2011/03/google-adsense.jpg"));
That image URL doesn't work for me.
I would recommend going another route for downloading an image from the internet. If you call setImageURI from getView it will be running on the UI thread, which will cause your app to freeze until the image is returned from the network. Also, the image won't be cached so you could potentially download the same image over and over.
Check out this ImageLoader library for Android which can simplify downloading images. It handles downloading them in the background, it can process multiple request simultaneously, and it caches images for you.
How can I turn the static image
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.67"
android:src="#drawable/static_image" />
into an ImageView whose source can be dynamically set to data that is not already in the res folder?
That is, my application has an icon on the screen but the actual image for the icon is downloaded from an outside server and can change dynamically. How do I update the ImageView with the desired image upon download? I want something functionally like:
Image selectedImage = //get from server
myImageView.setImage(selectedImage);
Ur question is not clear. If u just wanna have an image(that is in some url) set to an image view,
Bitmap bmp=getBitmapFromURL(ur url here);
imgview.setImageBitmap(bmp);
and write this function:
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap mybitmap = BitmapFactory.decodeStream(input);
return mybitmap;
} catch (Exception ex) {
return null;
}
yourImageView.setImageBitmap(bitmap);
to get Bitmap from server:
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;
}
As per I understand your question something like,
ImageView selectedImage;
selectedImage = (ImageView)findViewById(R.id.imageView1);
Bitmap bmImg;
downloadFile(imageUrl);
And this is downloadFile() Method...
void downloadFile(String fileUrl){
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();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
selectedImage.setImageBitmap(bmImg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
You need to create a custom view and over-ride onDraw(). From there you are provided the drawing Canvas and you can do whatever you like. So assuming your dynamic image can be converted to a bitmap, there are numerous drawBitmap() methods you can use from Canvas.
Note that you must also override onMeasure() which allows your view to tell the layout manager how much space you need.
There's a lot of good info here:
http://developer.android.com/guide/topics/ui/custom-components.html
This question already has answers here:
Write to /res/drawable/ on the fly?
(3 answers)
Closed 9 years ago.
I want to save image into my local drive folder or to res/drawable folder in my application. I'm right now saving img into sd card but I've to save it in res/drawable folder.
My code is:
String image_URL = "http://chart.apis.google.com/chart?chs=200x200&cht=qr&chl=http%3A%2F%2Fandroid-er.blogspot.com%2F";
String extStorageDirectory;
Bitmap bm;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonSave = (Button) findViewById(R.id.save);
ImageView bmImage = (ImageView) findViewById(R.id.image);
BitmapFactory.Options bmOptions;
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
bm = LoadImage(image_URL, bmOptions);
bmImage.setImageBitmap(bm);
extStorageDirectory = Environment.getExternalStorageState().toString();
extStorageDirectory = Environment.getExternalStorageDirectory()
.toString();
buttonSave.setText("Save to " + extStorageDirectory + "/qr.PNG");
buttonSave.setOnClickListener(buttonSaveOnClickListener);
}
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;
}
Button.OnClickListener buttonSaveOnClickListener = new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
OutputStream outStream = null;
File file = new File(extStorageDirectory, "er.PNG");
try {
outStream = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
Toast.makeText(LoadSaveImgActivity.this, "Saved",
Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(LoadSaveImgActivity.this, e.toString(),
Toast.LENGTH_LONG).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(LoadSaveImgActivity.this, e.toString(),
Toast.LENGTH_LONG).show();
}
}
};
Its not possible.
The following link can be helpful
Write to /res/drawable/ on the fly?
It is not possible to save anything into res/drawable at runtime, sorry.
You can't modify neither res/drawable, nor any other folder of your apk at runtime. It is build at compile-time and nothing can modify it from inside the application after.
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.