首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将bundle.getString()的结果分配给字符串将引发一个ClassCastException

将bundle.getString()的结果分配给字符串将引发一个ClassCastException
EN

Stack Overflow用户
提问于 2019-07-22 16:40:49
回答 1查看 119关注 0票数 0

我有一个名为Place ObjectspiliaBeach实例,它接受下面看到的参数:

代码语言:javascript
运行
复制
public PlaceObject spiliaBeach = new PlaceObject(R.string.spilia_beach,R.string.spilia_description,"2 Km from the Port",R.string.beach_category);

PlaceObject.java类:

代码语言:javascript
运行
复制
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,如下所示:

代码语言:javascript
运行
复制
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中这样检索它:

代码语言:javascript
运行
复制
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,表示返回的字符串不能在该行中没有任何整数是整数时转换给整数,对吗?知道为什么吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-07-22 16:43:35

声明您的PlaceObject类为Parcelable,并按照指南https://www.vogella.com/tutorials/AndroidParcelable/article.html实现所有必需的方法

然后,您将能够将对象保存为

代码语言:javascript
运行
复制
intentBundle.putParcelable(placeObject);

并将其作为

代码语言:javascript
运行
复制
Bundle dataBundle = getIntent().getExtras();
PlaceObject object = (PlaceObject) dataBundle.getParcelable(KEY);

编辑:您传递为整数id的R.string.spilia_beach,以便获得字符串使用getString(R.string.spilia_beach)等

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57150336

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档