Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass non parcelable objects to from activity to another activity?

I have two objects instantiated from two different class and both classes do not implement parcelable nor serializable. and I want to pass those objects to another activity, so I wrote the below code:

*code:

 //send object
 Intent intConnect = new Intent(mCtx.getApplicationContext(), ActConnect.class);
            Bundle bndConnect = new Bundle();
            bndConnect.putParcelable("HeaderModel", (Parcelable) mHeaderModel);
            bndConnect.putParcelable("DetailsModel", (Parcelable) mDetailsModel);
            intConnect.putExtras(bndConnect);
            intConnect.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mCtx.startActivity(intConnect);

//receive objects in the receiving activity
 Bundle extras = getIntent().getExtras();
    Header headerModel = (Header) extras.get("HeaderModel");
    Details detailsModel = (Details) extras.get("DetailsModel");

but at run time, I receive the below logcat:

logcat:

10-08 11:55:44.225  13138-13138/com.example.com.bt_11 E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.com.bt_11, PID: 13138
java.lang.ClassCastException: com.example.com.adapter.Header cannot be cast to android.os.Parcelable
        at com.example.com.adapter.MyExpandableList$1.onClick(MyExpandableList.java:152)
        at android.view.View.performClick(View.java:5184)
        at android.view.View$PerformClick.run(View.java:20893)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)

how can I pass non parcelable objects to from activity to another activity?

like image 997
LetsamrIt Avatar asked Nov 22 '22 03:11

LetsamrIt


1 Answers

If your class doesn't implement parcelable nor serializable, and you cannot modify them (code not under your control perhaps), then you have no way to directly send the data between the two activities.

However, you can pass the data indirectly between the two activities. You could store them in a singleton class (however singletons are hard to test etc.), you could save and retrieve them off your application class, or you could persist them into sharedpreferences, a file or a database to be loaded by the second activity.

like image 57
Jon Finerty Avatar answered Dec 18 '22 06:12

Jon Finerty