Sobes.tech
Junior — Middle

What reasons make passing a Bitmap object through Intent impractical, and what alternatives exist for passing images between components?

sobes.tech AI

Answer from AI

Passing a Bitmap object through an Intent in Android is impractical for several reasons:

  • Large data size: Bitmap can occupy a lot of memory, leading to exceeding the Intent size limit (usually around 1 MB), which will cause a TransactionTooLargeException error.
  • Performance: Serializing and deserializing Bitmap in an Intent slows down the application.
  • Memory leak risk: Improper management of Bitmap can lead to leaks.

Alternatives for passing images between components:

  1. Passing URI or file path: Save the image in internal or external storage, pass the path or URI via Intent.
  2. Using Singleton or global storage: Store Bitmap in memory in a static field or through ViewModel (in case of Activity/Fragment).
  3. Using database or cache: Save the image in a database or cache memory, pass the identifier.

Example of passing URI:

// Save Bitmap to file
File file = new File(context.getCacheDir(), "image.png");
FileOutputStream fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();

// Pass URI via Intent
Intent intent = new Intent(context, TargetActivity.class);
intent.putExtra("image_uri", Uri.fromFile(file).toString());
startActivity(intent);

In TargetActivity, you can get the URI and load the image from the file.