Sidharth Sidharth - 2 months ago 24
Android Question

Load Image Into ImageView Android

I am trying to load an image from my local server into an image view using glide. The url i am using works fine. When i look for it in the browser the image loads, but when i use it in the code the glide does not load the image.

package knife.butter.glide;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

Button btn;
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

btn=(Button) findViewById(R.id.button);
imageView=(ImageView) findViewById(R.id.imageView);

btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

try {

Glide.with(v.getContext())
.load("http://192.168.1.191/driver/uploads/driver.jpg")
.placeholder(R.mipmap.ic_launcher)
.into(imageView);

} catch (Exception e) {
Toast.makeText(MainActivity.this,e.toString(),Toast.LENGTH_SHORT).show();
}


}
});
}
}

Answer

Here, use inbuilt listener of glide for checking Exception.

Glide.with(v.getContext())
     .load("http://192.168.1.191/driver/uploads/driver.jpg")
     .listener(new RequestListener<String, GlideDrawable>() {
         @Override
         public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
             Log.e("Error","invalid Image Link");
             return false;
         }

         @Override
         public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
             return false;
         }
     })
     .placeholder(R.mipmap.ic_launcher)
     .into(imageView);

Note :

Make sure you have Given permission

<uses-permission android:name="android.permission.INTERNET" />

in your manifest.xml

Happy Coding..

Comments