5

I use this code to display image from url it work but the image is stored in device this is the problem because I want to display this image only if the user is connected to internet

ImageView imageView=(ImageView) findViewById(R.id.imageView3);
image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
imageView.setImageBitmap(bitmap);

How do I display image from URL in Android?

jww
  • 97,681
  • 90
  • 411
  • 885
Ridae HAMDANI
  • 686
  • 2
  • 7
  • 17

9 Answers9

7
compile "com.squareup.picasso:picasso:2.4.0"

Use this library to load images.

Picasso.with(context)
       .load(url)
       .placeholder(R.drawable.placeholder) //optional
       .resize(imgWidth, imgHeight)         //optional  
       .centerCrop()                        //optional   
       .into(image);                        //Your image view object.
Manish
  • 234
  • 2
  • 13
Sagar Gangawane
  • 1,985
  • 1
  • 12
  • 22
6

Try this solution..

image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
imageView.setImageBitmap(image);

it will help you.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Atul Mavani
  • 1,437
  • 1
  • 10
  • 11
3

Glide library is better than Picasso I'm suggesting you to use Glide

for doing this in Build.gradle file in dependency section add this code:

compile 'com.github.bumptech.glide:glide:3.7.0'

then in your Activity that you want to show Image use this code in your onCreate method:

String myUrl = "https://github.com/bumptech/glide/raw/master/static/glide_logo.png";

ImageView imageView = (ImageView)findViewById(R.id.yourImageView);

Glide.with(getApplicationContext())
     .load(myUrl)
     .into(imageView);
Mahdi Nouri
  • 1,391
  • 14
  • 29
1

You can use Picasso library to load image into imageView. It is easy to use.

Add dependency in your app level build.gradle file

compile 'com.squareup.picasso:picasso:2.5.2'

Load image from a url like this

Picasso.with(this).load(url).into(imageView);

Read more about Picasso enter link description here

saty
  • 66
  • 7
  • 1
    `compile` is deprecated, replace with `implementation` =) – xjcl Jun 28 '20 at 21:10
  • Note that `into()` is **asynchronous** so putting `marker.showInfoWindow()` after it didn't work for me for example – xjcl Jun 28 '20 at 21:33
0

To check internet connectivity use following code

            ConnectivityManager connectivity = (ConnectivityManager) _Context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        if (connectivity != null) {
            NetworkInfo activeNetwork = connectivity.getActiveNetworkInfo();
            boolean isConnected = activeNetwork != null &&
                    activeNetwork.isConnectedOrConnecting();
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        available = true;
                    }
                }
            }
        }
        if (available == false) {
            NetworkInfo wiMax = connectivity.getNetworkInfo(6);
            if (wiMax != null && wiMax.isConnected()) {
                available = true;
            }
        }

And After that use to download image

class DownloadTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
String image_name, studentName;
TextDrawable drawable;

public DownloadTask(ImageView bmImage, String file_name) {
    this.bmImage = bmImage;
    this.image_name = file_name;
}

protected Bitmap doInBackground(String... urls) {
    InputStream input = new java.net.URL(image_name).openStream();
    if(input.available()!=0) {
        return BitmapFactory.decodeStream(input);
    }
    return null;
}

protected void onPostExecute(Bitmap result) {
    try {
        if(result == null)
            bmImage.setImageDrawable(drawable);
        else
        bmImage.setImageBitmap(result);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Attiq ur Rehman
  • 475
  • 1
  • 6
  • 21
0

I have also same problem solve using below code.

Picasso.with(context).load(uri).networkPolicy(NetworkPolicy.NO_CACHE)
        .memoryPolicy(MemoryPolicy.NO_CACHE)
        .placeholder(R.drawable.bv_logo_default)
        .into(viewImage_imageView);
Shabbir Dhangot
  • 8,954
  • 10
  • 58
  • 80
0

Try this also Fix the size according to you..or see the resize with universal loader

<ImageView
android:id="@id/ivImage"
android:layout_width="150dp"
android:layout_height="150dp"
android:adjustViewBounds="true"

android:scaleType="fitCenter" />

Used the Android Universal Image-Loader

Declare

    private ImageLoader imageLoader1;

On Create

 imageLoader1 = ImageLoader.getInstance();

 imageLoader1.init(ImageLoaderConfiguration.createDefault(youractivity.this));

no_image here a drawable image without any image load in Cache

   DisplayImageOptions
            options = new DisplayImageOptions.Builder()
            .cacheInMemory(true)
            .cacheOnDisk(true)
            .showImageOnLoading(R.drawable.no_image) // resource or drawable
            .showImageForEmptyUri(R.drawable.no_image) // resource or drawable
            .showImageOnFail(R.drawable.no_image)
            .considerExifParams(true)
            .bitmapConfig(Bitmap.Config.RGB_565)
            .build();

    imageLoader1.displayImage(yourpathURl.replace(" ", "%20"), ivImage, options);

Add gradle dependencies also... download the latest jar of universal loader

The download link of jar

  compile files('libs/universal-image-loader-1.9.5-with-sources.jar')

You Can Use Piccaso Also and Glide also

Arjun saini
  • 4,223
  • 3
  • 23
  • 51
0
Glide.with(context).load(uri).asBitmap().placeholder(R.drawable.yourimage).error(R.drawable.yourimage).into(yourview); 

Apart from the above answer if the image URL return null you can load default image into the view as like above.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Senthilvel S
  • 331
  • 1
  • 7
  • 21
0

I end up with something like this for kotlin.

//download
val result = lifecycleScope.async(Dispatchers.IO){
    try {
        val url = URL("url")
        return@async BitmapFactory.decodeStream(url.openConnection().getInputStream())
    } catch (e: IOException){
        println("Error")
    } catch (e: UnknownServiceException){
        println("Error2")
    } catch (e: MalformedURLException){
        println("Error3")
    }
}

lifecycleScope.launch {
    val bitmap = result.await() as Bitmap
    val imageView: ImageView = findViewById(R.id.post_image)
    imageView.setImageBitmap(bitmap)  
}
akuba
  • 111
  • 1
  • 8