Load image from auto download url - android

While calling my url, which downloads an image from server automatically. I need to display this image on an Android ImageView. I usually using Piccaso library to load image from url but that not helping me here, is there any way to load image from auto download url to an Android ImageView?
Auto download url example is in here(wallpaperswide.com/download/bike_chase-wallpaper-2560x1600.jpg)

Well if dont want to use library like Piccaso try something like this:
public class AsyncTaskLoadImage extends AsyncTask<String, String, Bitmap> {
private final static String TAG = "AsyncLoadImage";
private ImageView imageView;
public AsyncTaskLoadImage(ImageView imageView) {
this.imageView = imageView;
}
#Override
protected Bitmap doInBackground(String... params) {
Bitmap bitmap = null;
try {
URL url = new URL(params[0]);
bitmap = BitmapFactory.decodeStream((InputStream)url.getContent());
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
imageView.setImageBitmap(bitmap);
}
}
And you call in your activity like:
String url = "YOUR_LINK_HERE";
new AsyncTaskLoadImage(imageView).execute(url);
OR
With less code try something like this answer:
URL url = new URL("YOUR_LINK_HERE");
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
imageView.setImageBitmap(bmp);

Related

Asynctask Download and set Jpg as imageView

With help from internet, I can download a jpg and set it to ImageView with bitmap.
But, I want to keep it as jog or png.
How I can do that?
public class GetFlickr extends AsyncTask<String, String, Bitmap> {
private ProgressBar pBar;
private String file = "flickr.xml";
private WeakReference<ImageView> imageViewWeakReference;
GetFlickr(ImageView Iv){
imageViewWeakReference = new WeakReference<>(Iv);
}
#Override
protected void onPreExecute(){
super.onPreExecute();
pBar = findViewById(R.id.progressBar);
pBar.setProgress(0);
pBar.setVisibility(View.VISIBLE);
}
#Override
protected Bitmap doInBackground(String... strings) {
Bitmap bitmap=null;
try{
URL urlfinal = new URL("https://farm66.staticflickr.com/65535/49344706212_80c4e61053.jpg");
HttpURLConnection connection1 = (HttpURLConnection) urlfinal.openConnection();
connection1.connect();
//FileOutputStream fOut2= openFileOutput("flickr.jpg", MODE_PRIVATE);
InputStream fOut2 = urlfinal.openStream();
bitmap = BitmapFactory.decodeStream(fOut2);
} catch (MalformedURLException e){
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
return bitmap;
}
protected void onProgressUpdate(String... progress) {
pBar.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(Bitmap bitmap) {
ImageView Iv = imageViewWeakReference.get();
if (Iv != null){
Iv.setImageBitmap(bitmap);
}
pBar.setVisibility(View.GONE);
}
}
}
A good help will be the library Picasso
You can easily work with online images, automatic caching, etc.
just insert in your gradle:
implementation 'com.squareup.picasso:picasso:(insert latest version)'
and load your image like this
Picasso.get().load(/* here your url */).into(imageView1);
I suggest you use Glide library. it supports LruCache and diskCache.
dependencies {
implementation 'com.github.bumptech.glide:glide:4.10.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.10.0'
}
then load it as the following:
Glide
.with(myFragment)
.load(url)
.centerCrop()
.placeholder(R.drawable.loading_spinner)
.into(myImageView);

Display Images in Recyclerview without using any library [duplicate]

I'm trying to download an image using a URL and a button in my app. When I'm running it on my phone, I,m not able to download the image. Can anyone please point out the problem with this. Thanks for the help in advance :)
This is my code.
public class MainActivity extends AppCompatActivity {
ImageView download;
public void downloadImage(View view){
DownloadImage image = new DownloadImage();
Bitmap result;
try {
result = image.execute("https://en.wikipedia.org/wiki/File:Bart_Simpson_200px.png").get();
download.setImageBitmap(result);
}
catch(Exception e)
{
e.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
download = (ImageView) findViewById(R.id.imageView);
}
public class DownloadImage extends AsyncTask<String, Void, Bitmap>{
#Override
protected Bitmap doInBackground(String... urls) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoInput(true);
urlConnection.connect();
InputStream in = urlConnection.getInputStream();
Bitmap Image = BitmapFactory.decodeStream(in);
in.close();
return Image;
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}
you can download image from url in two ways
1.you can user Glide library to load image from url look the below code it can help you in simple way
compile this library
implementation 'com.github.bumptech.glide:glide:4.6.1'
than load image like this
Glide.with(MainActivity.this)
.load(url)
.apply(new RequestOptions().placeholder(R.drawable.booked_circle).error(R.drawable.booked_circle))
.into(imageview);
2 .try this if you dont want to use third party library
new DownloadImage(imamgeview).execute(url);
create a Async Task
public class DownloadImage extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImage(ImageView bmImage) {
this.bmImage = (ImageView ) 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);
}
}
i hope that it will work in your case
You did not call the function
downloadImage(view);
In the oncreate (after the findviewbyid line)
Also check if the internet permision is in the Android Manifest file :
<uses-permission android:name="android.permission.INTERNET" />
Having said that you should use a library like Glide\Picasso\Ion etc... much better than asynctask for this purpuse
https://github.com/bumptech/glide - Glide
https://github.com/koush/ion - Ion
http://square.github.io/picasso/ - picasso
Hope it helped.

Load images in listview only when they are about to display

I am working on making a music player and what i have done so far is that I created a song list in listview with their thumbnail images using metadata files.
Now when i scroll my list it lags, that might be because of the image loading.
I referred to Google Play Music App and what they have done is that they fetch album art at the time of scrolling so scrolling is smooth.
Is there any way to implement that kind of functionality?
You have to use lazy loading of images, so images will be downloaded in background.
public class DownloadImage extends AsyncTask<ImageView, Void, Bitmap> {
ImageView imageView = null;
#Override
protected Bitmap doInBackground(ImageView... imageViews) {
this.imageView = imageViews[0];
return download_Image((String) imageView.getTag());
}
#Override
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
private Bitmap download_Image(String url) {
try {
URL ulrn = new URL(url);
HttpURLConnection con = (HttpURLConnection) ulrn.openConnection();
InputStream iS = con.getInputStream();
Bitmap bmp = BitmapFactory.decodeStream(iS);
return bmp;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
}
Make a call to this class in your adapter getview
imgThumbnail.setTag(<your image url>);
new DownloadImage().execute(imgThumbnail);

Set Linear layout background dynamically

I wanted to set Linear Layout background dynamically in the following way:
Fetch image from web url through XML parsing and then store that image into sd card.
Now the image saved into sd card.
Set that image as a linear layout background in the app.
Now I am stuck in the third step. Can anyone help?
Use this:
Bitmap bmImg = BitmapFactory.decodeStream(is);
BitmapDrawable background = new BitmapDrawable(bmImg);
linearLayout.setBackgroundDrawable(background);
Also check this: How to convert a Bitmap to Drawable in android?
I have done this way:
private RelativeLayout relativeLayout;
onCreate:
relativeLayout= (RelativeLayout)findViewById(R.id.relativeLayout);
new LoadBackground("http://www.tmonews.com/wp-content/uploads/2012/10/androidfigure.jpg",
"androidfigure").execute();
AsyncTask to load image in background:
private class LoadBackground extends AsyncTask<String, Void, Drawable> {
private String imageUrl , imageName;
public LoadBackground(String url, String file_name) {
this.imageUrl = url;
this.imageName = file_name;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Drawable doInBackground(String... urls) {
try {
InputStream is = (InputStream) this.fetch(this.imageUrl);
Drawable d = Drawable.createFromStream(is, this.imageName);
return d;
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
private Object fetch(String address) throws MalformedURLException,IOException {
URL url = new URL(address);
Object content = url.getContent();
return content;
}
#Override
protected void onPostExecute(Drawable result) {
super.onPostExecute(result);
relativeLayout.setBackgroundDrawable(result);
}
}
Hope this will help you.
An easier way:
BitmapDrawable d = new BitmapDrawable("/sdcard/data/image.jpg");
linearLayout.setBackgroundDrawable(d);
API are deprecated you can use the below code
BitmapDrawable background = new BitmapDrawable(getResources(), bitmapImage);
linearLayout.setBackground(background);
Try to use this:
Bitmap bmpOriginal = BitmapFactory.decodeResource(getResources(), R.drawable.img);
BitmapDrawable bmpBackground = new BitmapDrawable(getResources(), bmpOriginal)
Use #Deimos's answer, but like this since some methods are deprecated now
Bitmap bmImg = BitmapFactory.decodeStream(is);
BitmapDrawable background = new BitmapDrawable(context.getResources(), bmImg);
linearLayout.setBackground(background);
You can also set image from drawable folder.
yourView.setBackgroundResource(R.drawable.FILENAME);
That set FILENAME as background image.

Android : Loading an image from the Web with Asynctask

How do I replace the following lines of code with an Asynctask ?
How do you "get back" the Bitmap from the Asynctask ? Thank you.
ImageView mChart = (ImageView) findViewById(R.id.Chart);
String URL = "http://www...anything ...";
mChart.setImageBitmap(download_Image(URL));
public static Bitmap download_Image(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("Hub","Error getting the image from server : " + e.getMessage().toString());
}
return bm;
//---------------------------------------------------
}
I thought about something like this :
replace :
mChart.setImageBitmap(download_Image(graph_URL));
by something like :
mChart.setImageBitmap(new DownloadImagesTask().execute(graph_URL));
and
public class DownloadImagesTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... urls) {
return download_Image(urls[0]);
}
#Override
protected void onPostExecute(Bitmap result) {
mChart.setImageBitmap(result); // how do I pass a reference to mChart here ?
}
private Bitmap download_Image(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("Hub","Error getting the image from server : " + e.getMessage().toString());
}
return bm;
//---------------------------------------------------
}
}
but How do I pass a reference to mChart in onPostExecute(Bitmap result) ???
Do I need to pass it with the URL in some way ?
I would like to replace all my lines of code :
mChart1.setImageBitmap(download_Image(URL_1));
mChart2.setImageBitmap(download_Image(URL_2));
with something similar ... but in Asynctask way !
mChart1.setImageBitmap(new DownloadImagesTask().execute(graph_URL_1));
mChart2.setImageBitmap(new DownloadImagesTask().execute(graph_URL_2));
Is there an easy solution for this ?
Do I get something wrong here ?
If there is no good reason to download the image yourself then I would recommend to use Picasso.
Picasso saves you all the problems with downloading, setting and caching images.
The whole code needed for a simple example is:
Picasso.with(context).load(url).into(imageView);
If you really want to do everything yourself use my older answer below.
If the image is not that big you can just use an anonymous class for the async task.
This would like this:
ImageView mChart = (ImageView) findViewById(R.id.imageview);
String URL = "http://www...anything ...";
mChart.setTag(URL);
new DownloadImageTask.execute(mChart);
The Task class:
public class DownloadImagesTask extends AsyncTask<ImageView, Void, Bitmap> {
ImageView imageView = null;
#Override
protected Bitmap doInBackground(ImageView... imageViews) {
this.imageView = imageViews[0];
return download_Image((String)imageView.getTag());
}
#Override
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
private Bitmap download_Image(String url) {
...
}
Hiding the URL in the tag is a bit tricky but it looks nicer in the calling class if you have a lot of imageviews that you want to fill this way. It also helps if you are using the ImageView inside a ListView and you want to know if the ImageView was recycled during the download of the image.
I wrote if you Image is not that big because this will result in the task having a implicit pointer to the underlying activity causing the garbage collector to hold the whole activity in memory until the task is finished. If the user moves to another screen of your app while the bitmap is downloading the memory can't be freed and it may make your app and the whole system slower.
Try this code:
ImageView myFirstImage = (ImageView) findViewById(R.id.myFirstImage);
ImageView mySecondImage = (ImageView) findViewById(R.id.mySecondImage);
ImageView myThirdImage = (ImageView) findViewById(R.id.myThirdImage);
String URL1 = "http://www.google.com/logos/2013/estonia_independence_day_2013-1057005.3-hp.jpg";
String URL2 = "http://www.google.com/logos/2013/park_su-geuns_birthday-1055005-hp.jpg";
String URL3 = "http://www.google.com/logos/2013/anne_cath_vestlys_93rd_birthday-1035005-hp.jpg";
myFirstImage.setTag(URL1);
mySecondImage.setTag(URL2);
myThirdImage.setTag(URL3);
new DownloadImageTask.execute(myFirstImage);
new DownloadImageTask.execute(mySecondImage);
new DownloadImageTask.execute(myThirdImage);
public class DownloadImagesTask extends AsyncTask<ImageView, Void, Bitmap> {
ImageView imageView = null;
#Override
protected Bitmap doInBackground(ImageView... imageViews) {
this.imageView = imageViews[0];
return download_Image((String)imageView.getTag());
}
#Override
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
private Bitmap download_Image(String url) {
Bitmap bmp =null;
try{
URL ulrn = new URL(url);
HttpURLConnection con = (HttpURLConnection)ulrn.openConnection();
InputStream is = con.getInputStream();
bmp = BitmapFactory.decodeStream(is);
if (null != bmp)
return bmp;
}catch(Exception e){}
return bmp;
}
}
you can create a class say..BkgProcess which contains an inner class that extends AsyncTask. while instantiating BkgProcess pass the context of your Activity class in BkgProcess constructor. for eg:
public class BkgProcess {
String path;
Context _context;
public Download(Downloader downloader, String path2){
this.path = path2;
_context = downloader;
}
public void callProgressDialog(){
new BkgProcess().execute((Void)null);
}
class Downloads extends AsyncTask<Void, Void, Boolean> {
private ProgressDialog dialog = new ProgressDialog(_context);
protected void onPreExecute(){
dialog.setMessage("Downloading image..");
dialog.show();
}
protected void onPostExecute(Boolean success) {
dialog.dismiss();
if(success)
Toast.makeText(_context, "Download complete", Toast.LENGTH_SHORT).show();
}
#Override
protected Boolean doInBackground(Void... params) {
return(startDownload(path));
}
public boolean startDownload(String img_url) {
// download img..
return true;
}
}
}
from your activity class..
BkgProcess dwn = new BkgProcess (Your_Activity_class.this, img_path);
dwn.callProgressDialog();
This will get you images of any size...
if you dont want the progress dialog just comment the codes in onPreExecute();
for(int i = 0 ; i < no_of_files ; i++ )
new FetchFilesTask().execute(image_url[i]);
private class FetchFilesTask extends AsyncTask<String, Void, Bitmap> {
private ProgressDialog dialog = new ProgressDialog(FileExplorer.this);
Bitmap bitmap[];
protected void onPreExecute(){
dialog.setMessage("fetching image from the server");
dialog.show();
}
protected Bitmap doInBackground(String... args) {
bitmap = getBitmapImageFromServer();
return bitmap;
}
protected void onPostExecute(Bitmap m_bitmap) {
dialog.dismiss();
if(m_bitmap != null)
//store the images in an array or do something else with all the images.
}
}
public Bitmap getBitmapImageFromServer(){
// fetch image form the url using the URL and URLConnection class
}

Categories

Resources