我有一个名为Place Object的spiliaBeach实例,它接受下面看到的参数:
public PlaceObject spiliaBeach = new PlaceObject(R.string.spilia_beach,R.string.spilia_description,"2 Km from the Port",R.string.beach_category);PlaceObject.java类:
private int name = 0;
private int description = 0;
private String locationDistance = "distance";
private int category = 0;
PlaceObject(int name, int description, String locationDistance, int category) {
this.name = name;
this.description = description;
this.locationDistance = locationDistance;
this.category = category;
}在MainActivity中,我将数据通过Bundle传递给我的DetailsActivity,如下所示:
Intent detailsIntent = new Intent(this, DetailsActivity.class);
Bundle intentBundle = new Bundle();
intentBundle.putInt("name",beachDB.spiliaBeach.getName());
intentBundle.putInt("description",beachDB.spiliaBeach.getDescription());
intentBundle.putString("distance",beachDB.spiliaBeach.getLocationDistance());
//Log.d(TAG,"Location distance : " + beachDB.spiliaBeach.getLocationDistance());
//intentBundle.putInt("category",beachDB.spiliaBeach.getCategory());
detailsIntent.putExtra("data",intentBundle);
startActivity(detailsIntent);并尝试在onCreate() of DetailsActivity中这样检索它:
private void getIntentData(Intent intent) {
Bundle dataBundle = intent.getBundleExtra("data");
if(dataBundle != null) {
name = dataBundle.getInt(NAME_KEY);
description = dataBundle.getInt(DESC_KEY);
locationDistance = dataBundle.getString(LOC_DIST_KEY);
Log.d(TAG, "location distance : " + locationDistance + '\n' + "description : " + description);
} else {
Log.d(TAG,"Bundle is null");
}
}但是logcat说locationDistance变量是null,它抛出一个ClassCastException,表示返回的字符串不能在该行中没有任何整数是整数时转换给整数,对吗?知道为什么吗?
发布于 2019-07-22 16:43:35
声明您的PlaceObject类为Parcelable,并按照指南https://www.vogella.com/tutorials/AndroidParcelable/article.html实现所有必需的方法
然后,您将能够将对象保存为
intentBundle.putParcelable(placeObject);并将其作为
Bundle dataBundle = getIntent().getExtras();
PlaceObject object = (PlaceObject) dataBundle.getParcelable(KEY);编辑:您传递为整数id的R.string.spilia_beach,以便获得字符串使用getString(R.string.spilia_beach)等
https://stackoverflow.com/questions/57150336
复制相似问题