Hamid
Hamid

Reputation: 4430

Android, want to reference Bitmaps in array using strings, programatically

I'm looking for a nice programatic way I can use to refer to the images in my Bitmap[].

At the moment, I declare a bunch of integers in my class

Bitmap[] mBmp = new Bitmap[6]    
int image1 = 0, image2 = 1, image3 = 2, someimage = 3, otherimage = 4, yetanoimage = 5;

I then refer to them as follows:

mBmp[someimage] ...

However, this is inefficient and I would like to refer to them (preferrably) according to their filename (minus the extension) or some other unique identifier than can be programatically determined.

The reason for this is that:

  1. number of images is arbitrary
  2. file names are arbitrary
  3. I want to automate the process as a template.

Upvotes: 3

Views: 3293

Answers (2)

Nick Campion
Nick Campion

Reputation: 10479

My recommendation would be to put your images into a HashMap. A Map is like an Array but with an object that works as the key. In this case, I'm suggesting you use a String object as the key. Map is the collection type, and HashMap is an implementation of Map.

To create a hashmap you'd do something like:

Map<String, Bitmap> myPictures = new HashMap<String, Bitmap>();

To Insert an image:

String fileName = "somefileName";
Bitmap bitmap = Bitmap bitmap = BitmapFactory.decode(fileName)
myPictures.put(fileName, bitmap)

Retrieving a bitmap can then be done like so:

Bitmap myBitmap = myPictures.get(filename)

You can iterate over the bitmaps by doing:

for(Bitmap bitmap : myPictures.values()){
   display(bitmap);
}

Upvotes: 3

punnie
punnie

Reputation: 2414

Do you have to use an array? Why don't you use an Hashtable to store your bitmaps? That way you could fetch them using their (unique) filename as their identifier.

As per the example, inserting bitmaps:

Hashtable<String, Bitmap> bitmaps = new Hashtable<String, Bitmap>();
numbers.put("one_image", bitmap1);
numbers.put("image_two", bitmap2);
numbers.put("beach_house", bitmap3);

And fetching bitmaps:

bitmap = bitmaps.get("beach_house");

Upvotes: 2

Related Questions