0

I have the following case:

Activity1

public class Activity1 extends Activity{
  ImageUtils.setArt(bitmap);
}

Activity2

public class Activity2 extends Activity{
  Bitmap b= ImageUtils.getArt();
}

ImageUtils

public class ImageUtils{
  private static Bitmap mArtWork;
  public static Bitmap getArt(){
    return mArtWork;
}

public static void setArt(Bitmap art){
  this.mArtWokr=art;
}

Now, I need a good approach, to share Bitmaps among different Activitys.

Since static variables will not be Garbage Collected during my application execution, I need a good way to share the images amongst my scenarios.

I am considering using a singleton "ImageUtils" to hold my images, and then access then.

I have considered and disregarded passing pareaceable bitmaps, and even sharing URI through intents, but those have had bad results.

Are there better approaches?

Bonatti
  • 2,778
  • 5
  • 23
  • 42

2 Answers2

1

Try to use Memory Cache (LRU cache for example) or Disk cache (File I/O for example). This is the suggested way by Google about how to caching bitmaps. The google documents is here.

  1. Save the bitmap in the cache in your Activity1
  2. Get the bitmap in the cache in Activity2, if its null, download it again

Set size of yur LRU cache. If the whole images size exceed the maiximun of the LRU cache you set, the least recently used images will be deleted.That's how LRU cache works. While if you save the images on the disk, don't forget to delete the images when you finish using them.

Community
  • 1
  • 1
Chenmin
  • 121
  • 7
  • but what issue could be with my approach and i m loading images from phone and i need to show one image at a time ? – angry_coder Sep 13 '16 at 12:37
  • If you are reading images from the phone, why pass the image from Acticity1 to Activity2. Just pass the path of the image. Read it from Activity2. If you still want to use your singleton class, after finishing using the bitmap, set it to null in your singleton class, otherwise it may cause OOM problem. Hope it helps. – Chenmin Sep 13 '16 at 14:43
0

It's not a good idea to pass a bitmap through memory, because bitmap isn't been compress in memory. Maybe try to save it into a temp file, and load in another activity...

RRTW
  • 3,160
  • 1
  • 35
  • 54
  • Why would you say that the extra overhead created by the file I/O is better than using the static field? – Tim Sep 13 '16 at 09:54
  • That's depends on the bitmap size, it could bring OutOfMemoryError if it is too large... If size isn't an issue, it's better to pass it through memory of course. – RRTW Sep 13 '16 at 09:59