yital9
yital9

Reputation: 6712

Android: How to pass Parcelable object to intent and use getParcelable method of bundle?

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?

Upvotes: 75

Views: 107781

Answers (5)

yorkw
yorkw

Reputation: 41126

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");

Upvotes: 174

Sohail Pathan
Sohail Pathan

Reputation: 336

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)

Upvotes: 0

chry
chry

Reputation: 434

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);
        }
    }

Upvotes: -1

Zar E Ahmer
Zar E Ahmer

Reputation: 34370

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";

Upvotes: -1

MAC
MAC

Reputation: 15847

Parcelable p[] =getIntent().getParcelableArrayExtra("parcel");

Upvotes: 1

Related Questions