gpt4 book ai didi

java - 将bundle.getString()的结果分配给String会抛出ClassCastException

转载 作者:行者123 更新时间:2023-12-02 09:40:04 31 4
gpt4 key购买 nike

我有一个名为 spiliaBeachPlace Object 实例,它接受您在下面看到的参数:

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);

并尝试在 DetailsActivityonCreate() 中像这样检索它:

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 表明返回的 String 不能转换为 Integer当该行中没有直接的整数时,对吧?有什么想法吗?

最佳答案

将您的 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)等

关于java - 将bundle.getString()的结果分配给String会抛出ClassCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57150336/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com