1

I have an idea about the widget that when I click on widget, the text & image will refresh randomly. I have done this with text, but my images are stored on Firebase and I want to take these random images and display them in an ImageView. So how I can do this?

Screenshot of my Firebase Storage:

base

Screenshot of my App:

app

Tom Fuller
  • 5,291
  • 7
  • 33
  • 42

2 Answers2

0

To randomly select an image from Firebase storage, you need to have a list of download url's of the files somewhere. As described in this answer, there is no Api to get a list of these pictures at the moment, so you will have to store the urls of them somewhere.

One possibility for this is to simply add the urls of the files to Firebase database. When you want to select a random image, you could go through the database, and select a random url from this list.

To actually display them in the ImageView, you can use a library like Glide, to make this process easier. The FriendlyPix example App by Firebase, shows how to do this.

Bernd
  • 779
  • 5
  • 11
0

As an alternative to @Bernd's answer: You could modify your image names to a standard naming scheme using incremental numbers. You could then retrieve the image URLs dynamically, like so:

Example image names:
image_0.jpg
image_1.jpg
image_2.jpg
image_3.jpg

Some example Java code to generate a random image filepath:

//The amount of images you have stored
int maxImages = 4; //Amount of images
Random random = new Random();
//Randomly generate a filepath to an image
String imageFilePath = "image_" + random.nextInt(maxImages) + ".jpg";

You can then use your generated imageFilePath with FireBase Storage's getDownloadUrl() to retrieve the proper download URL. You can then pass the URL to Glide, Picasso, or another image download library to load it into your ImageView.

Advantages

  • Only have to use Firebase Storage to achieve your goal

  • Less overhead on the database, don't have to maintain a list of images there

Disadvantages

  • You have to control the image names tightly, no custom image names

  • You have to have a fixed number of images

  • Could break if you delete an image without changing other image names

  • Retrieving the URL will throw an exception if the image couldn't be found (e.g. if the random number is out of bounds)