The images not showing from SQLite when store it as URL - java

When retrieving the images from Firebase to SQlite it comes as link, so I am trying now to show the images through Picasso as the following:
Picasso.with(context).load(favoritesList.get(position).getFoodImage())
.into(viewHolder.food_image);
but the image not showing. why its not showing? and how can i solve this issue?

Try this code and used Glide it is latest ..
add below dependency into app level gradle file..
implementation 'com.github.bumptech.glide:glide:4.7.1'
and make sure your path is not empty for give firebase server ..
Glide.with(context).load(favoritesList.get(position).getFoodImage())
.into(viewHolder.food_image);
and adapter define constructor like below ..
public RecyclerViewAdpater(List<String> mStringList, Context mContext) {
this.mStringList = mStringList;
this.mContext = mContext;
}

You are using old library try this,
In Gradle
implementation 'com.squareup.picasso:picasso:2.71828'
In Java
Picasso.get()
.load(url)
.placeholder(R.drawable.user_placeholder)
.error(R.drawable.user_placeholder_error)
.into(imageView);
See more details Here.

Set Image from URL using Picasso like this
Picasso.with(context)
.load(favoritesList.get(position).getFoodImage())
.resize(width,height).into(viewHolder.food_image);
OR
Load Image from direct URL
URL url = new URL(favoritesList.get(position).getFoodImage().toString());
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
viewHolder.food_image.setImageBitmap(bmp);
Hope this may help you

Related

How to convert String to Uri which is taken from sqlite and set it in ImageView?

I was saving image Uri to SQLite as String which I picked from gallery and it was set as image to my ImageView. But from 2nd activity I'm taking the Image(Uri) as String and converting to Uri and setting to ImageView.
When I run the 2nd activity it is giving an error like
resolveUri failed on bad bitmap uri: content://com.miui.gallery.open/raw/06.jpg
The code is like.
String valueImage;
imageView.setImageURI(Uri.parse(valueImage));
Do I need to convert in another way?
Thank you.
You can use Glide. It's very easy and takes only one line.
String valueImage; // Get url fro SQLite
Glide
.With(this)
.Load(Uri.parse(valueImage))
.Apply(RequestOptions.CircleCropTransform()).Into(imageView);
The import statement is to put into the app module gradle file (app/build.gradle)
implementation 'com.github.bumptech.glide:glide:4.9.0'
Hope it helps !
Try Glide for your requirement
Import glide using gradle
implementation 'com.github.bumptech.glide:glide:4.8.0'
Then set image to imageview using this method
Glide.with(context)
.load(Uri.fromFile(new File(valueImage)))
.into(imageView);

How to connect Android Application to SSL server when you have a CA that isn't trusted by the system?

I’m trying to download images from a website which is secured with SSL. Downloading images is successful when I run the App on API 23(Android 6.0) or above, but when the App runs on lower APIs, I get SSLHandshakeException with the “java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.” message.
The solution is right under the fingertips. Try this link Security with HTTPS and SSL. Complete solution is provided here
You can also use DownloadManager to download images from Url and save
to sdcard
DownloadImages(PictureURL, ImageSavePath);
public void DownloadImages(String theUrl, String thePath) {
Uri Download_Uri = Uri.parse(theUrl);
DownloadManager downloadManager = (DownloadManager) myContext.getSystemService(myContext.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Download_Uri);
//Restrict the types of networks over which this download may proceed.
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
//Set whether this download may proceed over a roaming connection.
request.setAllowedOverRoaming(true);
//Set the local destination for the downloaded file to a path within the application's external files directory
String[] split = theUrl.split("/");
//request.setDestinationInExternalFilesDir(myContext, mySdCardImagePath, split[split.length - 1]);
//request.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES, split[split.length-1]);
File destinationFile = new File(thePath, split[split.length - 1]);
Uri uri = null;
// naugat does not need provider here
uri = Uri.fromFile(destinationFile);
request.setDestinationUri(uri);
//Set the title of this download, to be displayed in notifications (if enabled).
request.setTitle(split[split.length - 1]);
//Set a description of this download, to be displayed in notifications (if enabled)
request.setDescription(thePath);
request.setVisibleInDownloadsUi(true);
//Enqueue a new download and get the reference Id
long downloadReference = downloadManager.enqueue(request);
//Check_Image_Status(downloadReference);
}
// Glide Image loader
compile 'com.github.bumptech.glide:glide:3.7.0'
Use following code inside onBindViewHolder
int defaultImagePath = R.drawable.default_thumb;
int errorImagePath = R.drawable.damaged_image;
holder.mImageViewContactItem.setImageResource(defaultImagePath);
String uri = photoPath;
loadImageWithGlide(context, holder.mImageViewContactItem, uri, defaultImagePath,
errorImagePath);
public void loadImageWithGlide(final Context context, ImageView theImageViewToLoadImage,
String theLoadImagePath, int theDefaultImagePath, int tehErrorImagePath) {
if (context == null) return;
Glide.with(context) //passing context
.load(theLoadImagePath) //passing your url to load image.
.placeholder(theDefaultImagePath) //this would be your default image (like default profile or logo etc). it would be loaded at initial time and it will replace with your loaded image once glide successfully load image using url.
.error(tehErrorImagePath)//in case of any glide exception or not able to download then this image will be appear . if you won't mention this error() then nothing to worry placeHolder image would be remain as it is.
.diskCacheStrategy(DiskCacheStrategy.ALL) //using to load into cache then second time it will load fast.
//.animate(R.anim.fade_in) // when image (url) will be loaded by glide then this face in animation help to replace url image in the place of placeHolder (default) image.
//.fitCenter()//this method help to fit image into center of your ImageView
.into(theImageViewToLoadImage); //pass imageView reference to appear the image.
/* Normal way to Load Image with Glide.
Glide.with(theContext)
.load(theImagePath)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(theImageView);*/
}

Loading Images with Picasso into RecyclerView from External Drive - Android App

I recently had an issue where I couldn't work out how to add any photos I take with my app into the phone's gallery.
I have now achieved this. My issue though, is when I am retrieving the photos I take onto the app from a Firebase database.
I have the following code using picasso to get my photos (this is from an Adapter class):
#Override
public void onBindViewHolder(ImageViewHolder holder, int position) {
Upload uploadCurrent = mUploads.get(position);
holder.textViewName.setText(uploadCurrent.getName());
Picasso.with(mContext)
.load(uploadCurrent.getImageUrl())
.placeholder(R.mipmap.ic_launcher)
.fit()
.centerCrop()
.into(holder.imageView);
}
If I take photos with the stock camera on the phone and upload these to Firebase via the app, when I come to retrieve them and show on my phone, they are fine. However, if I take a picture with the app I created, it uploads to the Firebase database okay but won't retrieve the picture. There is the placeholder for it with the image title but no actual image. I'm wondering whether it's something to do with the orientation but I'm not sure.
Has anyone got any suggestions? All welcome.
Thanks
On further research, I decided to give Glide a try instead of Picasso and it worked.
So, instead of the above, replace 'Picasso' with 'Glide' and '.fit()' with '.fitCenter()'.
Also, add the following to the gradle (using the latest versions):
implementation 'com.android.support:support-v4:27.0.2'
compile 'com.github.bumptech.glide:glide:3.7.0'
and change this line:
Picasso.with(this).load(mImageUri).into(mImageView);
to this:
Glide.with(this).load(mImageUri).dontAnimate().into(mImageView);
I hope that helps someone else in the future.

Glide not updating image android of same url?

I have the same url for an image. When I update this image more than one time it shows the previous image. The image and picture version on the server is updated but Glide is not showing the new image.I want to get new image every time and cache it .
Glide.with(context)
.load(Constants.COPY_LINK_BASE_URL + info.getDisplayPicture())
.placeholder(R.drawable.ic_profile).dontAnimate()
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.signature(new (SettingManager.getUserPictureVersion(context)))
.into(ivUserProfilePhoto);
I can reproduce this bug by changing internet ,on one internet its change image as expected on other internet it remain same after 2 or 3 tries to changing image
//Use bellow code, it work for me.Set skip Memory Cache to true. it will load the image every time.
Glide.with(Activity.this)
.load(theImagePath)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(myImageViewPhoto);
Glide 4.x
Glide.with(context)
.load(imageUrl)
.apply(RequestOptions.skipMemoryCacheOf(true))
.apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.NONE))
.into(imageView);
Glide 3.x
Glide.with(context)
.load(imageUrl)
.skipMemoryCache(true)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.into(imageView);
TL;DR.
you can skip caching by adding the following lines:
GLIDE v4
Glide.with(context)
.load(url)
.apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.NONE))
.apply(RequestOptions.skipMemoryCacheOf(true))
.into(imageView);
GLIDE v3
Glide.with(context)
.load(url)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(imageView);
OR : you can workaround caching by adding a dummy random argument to your URL:
Glide.with(context)
.load(url + "?rand=" + (new Random().nextInt()))
.into(imageView);
What's happening?
When your picture is loaded the first time, it's stored locally in what's called a cached memory (or simply "a cache"). When you request it for a second time Glide fetches if from the cache as if it was a successful request. This is meant for many good reasons such as: offloading your server, saving your users some data and responding quickly (offering your users a smooth experience).
What to do?
Now, concerning your issue: you need to disable the cache in order to force Glide to fetch your image remotely every time you ask for it. You can do the following:
Glide.with(context)
.load(url)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.signature(imageVersion) // supposing that each new image has its own version number
.into(imageView);
Or, in the case where you can't know when a picture is changes (no imageVersion), use a unique signature for each picture.
Glide.with(context)
.load(url)
.signature(new StringSignature(String.valueOf(System.currentTimeMillis())))
.into(imageView);
Another clean way would be to configure your picture's cache strategy in your server and use .diskCacheStrategy(DiskCacheStrategy.SOURCE).
A hacky trick worth mentioning
If adding a dummy GET paramter to your target URL doesn't break anything, then you could simply workaround caching by passing a random argument each time you fetch the image, this will push Glide to think you're querying a new endpoint, since the image cannot possibly exist in the cache.
Glide.with(context)
.load(url + "?rand=" + (new Random().nextInt())) // "&rand=" if your url already has some GET params
.into(imageView);
Glide caching API here.
I my case Glide not recognize .signature(), so additionally to #MGDavies's answer you maybe need something like this
// in kotlin
Glide.with(context)
.load("url")
//using apply to RequestOptions instead signature directly
.apply(RequestOptions().signature(ObjectKey("time that image was updated")))
.into(thumb)
This is an old question, so I'm sure you've got your fix by now. However I believe both of the big libraries(Picasso and Glide) now support something similar.
Glide has its signature API you may wish to look into:
https://github.com/bumptech/glide/wiki/Caching-and-Cache-Invalidation
Glide.with(yourFragment)
.load(yourFileDataModel)
.signature(new StringSignature(yourVersionMetadata))
.into(yourImageView);
I've not had a chance to work with this myself, but it looks as though you need to make a call to your API to get the version Metadata, then a subsequent call to fulfil it.
Alternatively, look into ETags.
Good luck!
Glide 4.8.0
Glide.with(mContext).asBitmap()
.load(nopicUrl)
.apply(RequestOptions.skipMemoryCacheOf(true))
.apply(RequestOptions.signatureOf(new ObjectKey(String.valueOf(System.currentTimeMillis()))))
.apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.DATA))
.into(ivImageView);
Now Glide latest version, you have to use RequestOption for clear cache.
RequestOptions options = new RequestOptions()
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true);
Or for everytime load picture you have to use a String in as signature.
RequestOptions options = new RequestOptions()
.signature(new StringSignature(String.valueOf(System.currentTimeMillis())));
Finally:
Glide.with(CompressSingleActivity.this)
.applyDefaultRequestOptions(options)
.load(currentFile)
.into(currentImageView);
When new images are loaded or updated, use below to clear Glide memory and cache :
|==| Clear Glide memory
Glide.get(getApplicationContext()).clearMemory();
|==| Clear Glide Cache()
void clearGlideDiskCache()
{
new Thread(new Runnable()
{
#Override
public void run()
{
Glide.get(getApplicationContext()).clearDiskCache();
}
}).start();
}
diskCacheStrategy and skipMemoryCache did not work for my case.
I was writing to a local image file between Glide requests with the same url. My hack of a solution was to switch between adding a 0/1 to the end of the filename.
Forcing it to change image source every time seems to work.
Try using RequestOptions:
RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(R.drawable.ic_placeholder);
requestOptions.error(R.drawable.ic_error);
Glide.with(context)
.setDefaultRequestOptions(requestOptions)
.load(url).into(holder.imageView);
If .setDefaultRequestOptions(requestOptions) does not work, use .apply(requestOptions):
Glide.with(MainActivity.this)
.load(url)
.apply(requestOptions)
.into(imageview);
// or this
Glide.with(MainActivity.this)
.load(url)
.apply(new RequestOptions().placeholder(R.drawable.booked_circle).error(R.drawable.booked_circle))
.into(imageview);
// or this
Glide.with(MainActivity.this)
.load(url)
.apply(RequestOptions.placeholderOf(R.drawable.booked_circle).error(R.drawable.))
.into(imageview);
it's like the issue is related to Glide Library itself, I found the trick that can fix this, just put a random number after your image URL as a query like an Example code below, it fixed my problem I hope it helps you too
Random random = new Random();
int randomInt = random.nextInt();
Glide.with(context)
.applyDefaultRequestOptions(new RequestOptions()
.circleCrop().diskCacheStrategy(DiskCacheStrategy.NONE))
.load(ConstantVars.BaseUrl + userModel.getAvatarURL() + "?" + randomInt)
.apply(new RequestOptions().error(R.drawable.himart_place_holder))
.into(imageViewProfile);
it will make Glide to reload image anytime you request like there's no cache at all to read from.

Android Picasso - Clear cache but image remains

So at certain times I need to clear the Picasso cache within my application, however when I clear it, the image is the same. If the image URL changes, then it pulls the new image but if the image url is the same, then the old image remains.
Can anyone help me clear the cache so that the image is removed?
This is how I set Picasso up:
Cache picassoCache = new LruCache(MEMORY_CACHE_SIZE);
picassoCacheClearer = new PicassoCacheClearerImpl(picassoCache);
picasso = new Picasso.Builder(context)
.downloader(new OkHttpDownloader(context.getCacheDir(), IMAGE_CACHE_SIZE))
.memoryCache(picassoCache)
.build();
and then try and clear it by:
cache.clear();
Below is the code which actually loads the image:
picasso.load(carouselAction.getImageUrl())
.placeholder(R.drawable.ic_placeholder)
.into(viewHolder.plistImageView);
I can see that the Invalidate() method is now deprecated, so what else can i do?
I have had this same problem and I used this hacky method to get around it. To force it to refresh i would just change the url adding a version tag to it. This is used commonly in web development to make sure things aren't used from the cache.
For example i would load an image from example.com/mypic.png?version=1234
and since the url is different it wouldn't load it from cache.
String versionTag = "?version=" + new Date().getTime();
picasso.load(carouselAction.getImageUrl() + versionTag)
.placeholder(R.drawable.ic_placeholder)
.into(viewHolder.plistImageView);
So found out what the issue was. Turns out for this carousel it was using a different instance of Picasso.
I also had to extend OkHttpDownloader to expose the getClient() method in order to get the cache to delete.
I realised it was a different instance of Picasso by enabling the indicators which can be done by setting the following in the builder
.indicatorsEnabled(true);

Categories