74

Why bundle has getParcelableArrayList, getParcelable methods; but Intent has only putParcelableArrayListExtra method? Can I transmit only object<T>, not ArrayList of one element? Then, what is getParcelable for?

AnV
  • 2,666
  • 3
  • 30
  • 40
yital9
  • 6,254
  • 15
  • 38
  • 51

5 Answers5

169

Intent provides bunch of overloading putExtra() methods.

Suppose you have a class Foo implements Parcelable properly, to put it into Intent in an Activity:

Intent intent = new Intent(getBaseContext(), NextActivity.class);
Foo foo = new Foo();
intent.putExtra("foo ", foo);
startActivity(intent);

To get it from intent in another activity:

Foo foo = getIntent().getExtras().getParcelable("foo");

Hope this helps.

weston
  • 52,585
  • 20
  • 135
  • 197
yorkw
  • 40,586
  • 10
  • 114
  • 130
  • 1
    I'm getting java.lang.ClassCastException: xxx.CDetails cannot be cast to android.os.Parcelable where CDetails is a type of custom model with key and value pairs. intent.putExtra("CDetails", (Parcelable) tempCDetails); – user1872384 Nov 24 '18 at 03:01
1
Parcelable p[] =getIntent().getParcelableArrayExtra("parcel");
MAC
  • 15,659
  • 8
  • 53
  • 95
0

Sender Activity:

val intent = Intent(this, RestaurantDetails::class.java)
        intent.putExtra(Constants.RESTAURANT, restaurant)
        startActivity(intent)

Receiver Activity:

        val restaurant = intent.getParcelableExtra<Restaurant>(Constants.RESTAURANT)

Sohail Pathan
  • 143
  • 1
  • 5
-1

It is important to remember that your models must implement the Parcelable interface, and the static CREATOR method. This case is for the lists

 private static final String MODEL_LIST = "MODEL_LIST";
    public MainFragment() {}

    public static MainFragment newInstance(ArrayList<YourModel>   
models) {
        MainFragment fragment = new MainFragment();
        Bundle args = new Bundle();
        args.putParcelableArrayList(MODEL_LIST,models);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            ArrayList<YourModel> models = getArguments().getParcelableArrayList(MODEL_LIST);
        }
    }
chry
  • 424
  • 7
  • 5
-2

First create Parcelable using Given Technique then

public static CreditCardDetail newInstance(CreditCardItemBO creditCardItem) {
        CreditCardDetail fragment = new CreditCardDetail();
        Bundle args = new Bundle();
        args.putParcelable(CREDIT_KEY,creditCardItem);
        fragment.setArguments(args);
        return fragment;
    }

And getting it like

 if(getArguments() != null)
 {
    creditCardItem = getArguments().getParcelable(CREDIT_KEY);               
 }

where

public static final String CREDIT_KEY = "creditKey";
Community
  • 1
  • 1
Zar E Ahmer
  • 32,807
  • 18
  • 222
  • 281