我有一个名为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()
的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
说当直接在该行中没有整数时,返回的字符串不能转换为整数。有什么想法吗? 最佳答案
将您的PlaceObject
类声明为Parcelable,并按照指南https://www.vogella.com/tutorials/AndroidParcelable/article.html实施所有必需的方法
然后,您将能够将对象另存为
intentBundle.putParcelable(placeObject);
并将其检索为
Bundle dataBundle = getIntent().getExtras();
PlaceObject object = (PlaceObject) dataBundle.getParcelable(KEY);
编辑:您传递
R.string.spilia_beach
这是整数id,为了获取字符串,请使用getString(R.string.spilia_beach)等