0

Creating intent with a large amount of data in extras

   public static Intent createIntent(Context context, List<PhotoItem> gallery, int indexOf) {
       Intent intent = new Intent(context, GalleryViewActivity.class);
       intent.putExtra(EXTRA_PHOTO_INDEX, indexOf);
       intent.putExtra(EXTRA_PHOTO_OBJECT, new Gson().toJson(gallery));
       return intent;
   }

Then running the activity: startActivity(createIntent(...

crashes application with error:

Exception when starting activity android.os.TransactionTooLargeException: data parcel size...

How to avoid such errors when data is too large in the list?

Morteza Rastgoo
  • 6,772
  • 7
  • 40
  • 61
  • You are passing whole `List` to your `GalleryViewActivity` with `Intent`. So it might possible that your list of `List` can have many data. So sometime system can now handle much data to transfer at a time. Might be the issue. – Ajay Mehta Apr 19 '19 at 09:33
  • Yes that is correct. – Morteza Rastgoo Apr 19 '19 at 09:34
  • But how to avoid such mistakes? – Morteza Rastgoo Apr 19 '19 at 09:34
  • 1
    You should avoid to pass large amount of data with `Intent`. You can use `SharedPreferences` to store your array list and retrieve the same on other activity. If you need i add answer for you with more detail for this. – Ajay Mehta Apr 19 '19 at 09:36
  • 1
    don't pass huge data between activities , also don't pass as a string , create a parcelable implementation , or use static fields or singletons – Manohar Apr 19 '19 at 09:36

1 Answers1

2

You are passing whole List<PhotoItem> to your GalleryViewActivity with Intent. So it might possible that your list of List<PhotoItem> can have many data. So sometime system can not handle much data to transfer at a time.

Please avoid to pass large amount of data with Intent.

You can use SharedPreferences to store your array list and retrieve the same on other activity.

Initialize your SharedPreferences using:

SharedPreferences prefrence =  PreferenceManager.getDefaultSharedPreferences(context);
Editor editor = prefrence.edit();

You can use this way to store list in Preference variable

public static Intent createIntent(Context context, List<PhotoItem> gallery, int indexOf) {
    Intent intent = new Intent(context, GalleryViewActivity.class);
    intent.putExtra(EXTRA_PHOTO_INDEX, indexOf);

    editor.putString("GallaryData", new Gson().toJson(gallery));
    editor.commit();

    return intent;
}

Now in your GalleryViewActivity.java file

SharedPreferences prefrence =  PreferenceManager.getDefaultSharedPreferences(context);
Editor editor = prefrence.edit();

String galleryData = prefrence.getString("GallaryData", "");
List<PhotoItem> listGallery = new Gson().fromJson(galleryData, new TypeToken<List<PhotoItem>>() {}.getType());

You will have your list in listGallery variable. You can retrieve your index as the same way you are using right now.

Ajay Mehta
  • 843
  • 5
  • 14