Search code examples
androidandroid-intentdeserializationparcelableparcel

Syntax for creating a Object implementing Parcelable from getParcelableExtra(intent_name)


I am implementing the DataDroid model of RESTful communication and I have come across a compiler error while implementing my SearchCriteria. The problem is that in order to pass the SearchCriteria around as an intent extra, I had to make it implement Parcelable. However, my Worker's start function requires a SearchCriteria class, leading to the error: Required: my.classes.SearchCriteria; Found: android.os.Parcelable.

Assuming that I've correctly implemented Parcelable for my SearchCriteria class, how can I quickly create an object from a parcel (where the parcel is found using getParcelable Extra(INTENT_NAME)?

Edit: I realize I can accomplish this quickly by making my constructor for SearchCriteria from Parcel public, but is there another way? Actually, this does not work - I confused a Parcel with a Parcelable thing.


Solution

  • Suppose you follow the API and make SearchCriteria implements Parcelable properly, and your SearchCriteria has been properly constructed or instantiated from the underlying business layer, either from a Database or a Http server or etc.

    To pass it to next activity by intent:

    SearchCriteria searchCriteria = createSearchCriteria();
    Intent intent = new Intent(getBaseContext(), NextActivity.class);
    intent.putExtra("searchCriteria", searchCriteria);
    startActivity(intent);
    

    To retrieve it from intent in next activity:

     SearchCriteria searchCriteria = getIntent().getParcelableExtra("searchCriteria");
     myWorker.search(searchCriteria);
    

    In most situation, we don't need bother Parcel directly.