75

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,794
  • 3
  • 32
  • 43
yital9
  • 6,544
  • 15
  • 41
  • 54

5 Answers5

174

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");
starball
  • 20,030
  • 7
  • 43
  • 238
yorkw
  • 40,926
  • 10
  • 117
  • 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,799
  • 8
  • 54
  • 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
  • 308
  • 2
  • 8
-1

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
  • 33,936
  • 20
  • 234
  • 300
-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
  • 434
  • 7
  • 5