android – 如何将非parcelable对象从活动传递到另一个活动?
作者:互联网
我有两个对象从两个不同的类实例化,这两个类不实现parcelable或serializable.我希望tp将这些对象传递给
另一个活动,所以我写了下面的代码:
*码:
//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");
但在运行时,我收到以下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)
如何将非可分配对象从活动传递到另一个活动?
解决方法:
你可以这样做:
您的Model类如下所示:
public class ModelClass implements Serializable{
// Other stuff
}
如何通过:
Intent mIntent = new Intent(mContext, NextActivity.class);
mIntent.putExtra("HeaderModel", mHeaderModel);
startActivity(mIntent);
如何获得:
Header headerModel = (Header) getIntent.getSerializableExtra("HeaderModel");
希望这会帮助你.
标签:android,android-intent,bundle,start-activity 来源: https://codeday.me/bug/20190628/1314739.html