Loading Image in Image View using Glide - java

I am working on an app which show an image which is loaded from my firebase database. I used Glide for that purpose.
I am using a button, on the click of that button a new activity will open which shows the image fetched from the url. The image load perfectly if url loaded correctly but if I cancelled in between, the app is crashing. Why it is happening and also, Is there any option to save the image in cache using glide, so that It can load it once and show without fetching it from firebase.
Here is my code to display image from url:
public void showImage(){
mStorageRef.child("TimeTable").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
url = uri.toString();
RequestOptions options = new RequestOptions().centerCrop().placeholder(R.mipmap.ic_launcher).error(R.mipmap.ic_launcher_round);
Toast.makeText(TimeTable.this, uri.toString(),Toast.LENGTH_SHORT).show();
Glide.with(TimeTable.this).load(url).apply(options).into(image);
}
});
}
Here is the Error log, when I closed the activity before image loaded completely..
Please ask if any further details are required.

You can cache your images loading using Glide. I am referring to the tutorial here where you can learn the basics of image caching using Glide.
Now about the crashing problem, it clearly says that you are trying to load something from an activity which is already destroyed. As you have a firebase listener added where you are loading the image, you need to destroy the listener as you are leaving the activity.
You might consider using onPause, onDestroy functions to handle the remove listener action. Check the removeEventListener function of Firebase.
However, I would recommend using activity scoped versions of the loaders so that Firebase task takes care of these things by itself. Please see the answer here.

Related

Is there any option for Glide if url is changed then cache will be cleared otherwise load with old image?

i am using glide for showing loading images, and in my app image will be changed frequently, is there any option for clear cache when new image or image will be edited otherwise load old one?
try this:
whenever image changes the cache will remove
Glide.with(YourActivity.this)
.load(Uri.parse(image_url))
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(mImage);
refer this link hope it will help you to resolve this issue
I have used the below code to achieve the same that you have mentioned in the description above.
fun ImageView.loadUrl(url: String) {
var requestOptions = RequestOptions()
requestOptions.signature(ObjectKey(System.currentTimeMillis()))
Glide.with(this).load(url).apply(requestOptions).into(this)
}
It's just an extension for the imageview and you need to use below way wherever you want this in your app.
imageView.loadUrl(url)

ImageView not Updating with new URL after activity is reopened

there are simple activities A and B. Activity A launches Activity B and i can select an image as profile image, which first I will upload it to the server and then show the image via the received url. At first when I switch to activity B everything works fine, if there is an image already downloaded its shown in the imageview or it will be downloded and shown. in this case if I select other images to upload, its working just fine and the imageview will show the new images. when I exit the activity and relaunch it, the previously downloded image is shown (if any exists), but any new image uploaded to server won't be shown not even drawables. the imageview won't update at all until I exit the activity again and relaunch it, which in this case the previous image uploaded will be shown but again no new image is shown. so to sum it, first time everything works fine, but for the next times the image is loaded properly only one time.
I've been using Glide and Frisco and thought the problem is caused by them but then used simple ImageView and simple connection to download bitmap and it was the same. it works only one time.
I've been testing both on Nokia 6.1 plus Android 9 and Nexus 5x Android 8.1 and emulators with Android 8.1 and Android 9. I've also tried the release build and still the same.In addition, I'm using AndroidX and the strategy to download image and load them is the same as my previous projects and I'd never faced this issue before.
tried these below before and after loading image and it's not working.
with Glide and Frisco the cache is also disabled. and The urls are completely random so they wont even have the chance to cache them.
here is a sample download and load, its just temporary.
image.setImageResource(0);
image.setImageBitmap(null);
image.invalidate();
new Thread(new Runnable() {
#Override
public void run() {
Bitmap bmp = null;
try {
trustEveryone();
URL url = new URL(user.image_address);
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
Bitmap finalBmp = bmp;
ProfileActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
_profileImage.setImageBitmap(null);
_profileImage.setImageResource(0);
_profileImage.invalidate();
_profileImage.setImageBitmap(finalBmp);
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
before using below method, tested it on my backup project before migrating to androidX and it was the same so the problem was not because of androidX
so here is the solution. the activities order : Main->Profile->Gallery->Crop->Back to Profile
to return the results from Crop to Profile I'm using event bus which has to be run on UI thread, so the Activity used to runOnUI... to post the event was CropActivity which was finished after the event is posted, and although I used ProfileActivity.runOnUI ... to load the image when receiving the event from event bus, the whole code was being run on CropActivity so I used another workaround to send results back to previous activity and that solved the problem without the need for invalidate or setting the image to null.

Prevent Android from showing sensible information on multi tasking view

I need to hide the content of my application when it goes to the background so sensitive information are not showing up on the android multitasking view.
It's been suggested to use the following line to hide the screen
getWindow().setFlags(LayoutParams.FLAG_SECURE, LayoutParams.FLAG_SECURE);
It works fine.
However, this prevents the user from taking screenshot as well which is not an expected behavior for me. I want to let the user take screenshot of the app if they need to. What I don't want is Android to display the latest screen on the multitasking view.
Would it be possible to set the FLAG_SECURE only when the app goes in the background?
We've ended up with this solution which worked the best for us:
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (!hasFocus) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE);
}
}
You can use Activity Lifecycle Callbacks. Just call setVisiblity(View.INVISIBLE) on the views that you want to hide in the onPause() Callback and setVisiblity(View.VISIBLE) in onResume() Callback.

Loading image using Picasso showing colors in corners

I use Picasso library for loading images in my app. But in some images,it shows a colored corner.See the red color in attached image. Does anyone know why this happens? How to sort this out?
Code:
Picasso picasso = Picasso.with(getActivity());
picasso.setDebugging(true);
picasso.load(downloadPath+imgDetailPhoto)
.placeholder(R.drawable.no_image)
.error(R.drawable.no_image)
.into(eventImage, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
Log.d("Error...", "picasso load error");
Picasso.with(getActivity()).load(R.drawable.no_image).into(eventImage);
}
});
Set picasso.setIndicatorsEnabled(false); in your picasso object.
Red color indicates that image is fetched from network.
Green color indicates that image is fetched from cache memory.
Blue color indicates that image is fetched from disk memory.
picasso.setDebugging(true); is deprecated
use picasso.setLoggingEnabled(true);
you have to disable indicators by calling the method picasso.setIndicatorsEnabled(false)
the ribbon is mean to show the image source. hope it helps
check this link, under the Debug Indicators they've mentioned it clearly
That's a debug indicator displayed by picasso to indicate whether the image is comming from the network, disk or memory. You can check it here http://square.github.io/picasso/ under 'Debug Indicators'
For development you can enable the display of a colored ribbon which indicates the image source. Call setIndicatorsEnabled(true) on the Picasso instance.

Display Video thumbnails from URL

Okay this might be a stupid one but kindly pardon me because I'm new to Android. I'm working on an App in which I want to display video thumbnails using remote URL's like:
Video URL:
http://173.193.24.66/~kanz/video/flv/9.flv
.JPG URL:
http://173.193.24.66/~kanz/video/Images/9.jpg
I have got both the video URL's and Image File URL's that I want to display on thumbnails stored on SQL database. The only thing is I don't know how to put them in List view inside a ScrollView. I tried searching on the Internet but they all seem to give tutorials on how to display video thumbnails from sd card path. I want to use any of these URL's to display video thumbnails.
I heard about API's but I can't use Youtube API since Youtube is banned in my country. If anyone knows any useful API or any other hack around, let me know. It would be highly appreciated. I'm using Gingerbread.
Add these lines to your Module:app gradle:
dependencies {
implementation 'com.github.bumptech.glide:glide:4.9.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0'
}
// pass video url into .load() method
Glide.with(context)
.asBitmap()
.load(/*Video Url*/)
.into(/*Name of Imageview*/);
Listview has its own scroll. So do not put listview inside a scroll view.
Use a custom listview to display the thumbnail.
Get your urls form the database.
http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/
http://www.youtube.com/watch?v=wDBM6wVEO70. The talk is about listview and performance.
Use a viewholder.http://developer.android.com/training/improving-layouts/smooth-scrolling.html.
If you are displaying lot of images in listview consider using one of the below libraries.
1.Universal Image loader. https://github.com/nostra13/Android-Universal-Image-Loader.
2.Lazy List. https://github.com/thest1/LazyList.
Both use caching.
For univarsal Image Loader
In your adapter constructor
File cacheDir = StorageUtils.getOwnCacheDirectory(a, "UniversalImageLoader/Cache");
imageLoader = ImageLoader.getInstance();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(a)
// You can pass your own memory cache implementation
.discCache(new UnlimitedDiscCache(cacheDir)) // You can pass your own disc cache implementation
.discCacheFileNameGenerator(new HashCodeFileNameGenerator())
.enableLogging()
.build();
// Initialize ImageLoader with created configuration. Do it once.
imageLoader.init(config);
options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.stub_id)//dummy image
.cacheInMemory()
.cacheOnDisc()
.displayer(new RoundedBitmapDisplayer(20))
.build();
In your getview()
ImageView image=(ImageView)vi.findViewById(R.id.imageview);
imageLoader.displayImage(imageurl, image,options);
Those tutorials are correct but you're missing a step. You need to download these images to the device first using the URL. Then you can set them up to be viewed in a listview.
See how to do this in these threads:
How to load an ImageView by URL in Android?
Android, Make an image at a URL equal to ImageView's image
There is a popular open source library that handles downloading and caching of images automatically. Check it out:
https://github.com/koush/UrlImageViewHelper

Categories

Resources