【问题标题】:Runtime exception : ClassCastException android.os.Bundle cannot be cast to Parcelable class运行时异常:ClassCastException android.os.Bundle 无法转换为 Parcelable 类
【发布时间】:2020-10-26 11:27:09
【问题描述】:

我在安装新代码并运行它时遇到了这个崩溃,下面我附上了旧代码和新代码。请让我知道我们该如何解决这些问题?

旧代码:

// data class
public class X {
  int val;
  ....
  ....
}

public final HelperClass {
  static Bundle toBundle(X obj) {
    toDataMap(obj).toBundle();
  }

  static DataMap toDataMap(X obj) {
    DataMap dataMap = new DataMap();
    dataMap.putInt("id", obj.val);
    ....
    ....
    return dataMap;
  }
}

// used in an activity on a onClick
context.startActivity(new Intent(ACTION_VIEW)
                         .putExtra(X_INSTANCE_EXTRA, HelperClass.toBundle(new X())));

// received in the activity started by the intent
X obj = bundle.getBundle(X_INSTANCE_EXTRA);

新代码:

// data class
public class X implements Parcelable {
  int val;
  ....
  ....

  @Override
  public void writeToParcel(Parcel dest, int flags) {
    dest.writeInt(val);
    ...
    ...
  }

  public static final Parcelable.Creator<X> CREATOR =
      new Parcelable.Creator<X>() {
        @Override
        public X createFromParcel(Parcel in) {
          X obj = new X();
          x.val = in.readInt();
          ...}
      };
}

// used in an activity on a onClick
context.startActivity(new Intent(ACTION_VIEW)
                         .putExtra(X_INSTANCE_EXTRA, new X());

// received in the activity started by the intent
X obj = intent.getParcelableExtra(X_INSTANCE_EXTRA);

我在新代码的最后一行得到错误说明

java.lang.ClassCastException: android.os.Bundle cannot be cast to X

是否因为某些意图在旧代码上触发并在新代码中接收?

【问题讨论】:

  • 看起来像。您是否在新旧代码之间卸载并重新安装了您的应用?
  • 但是我不希望我的用户面临这种崩溃,有没有办法处理这种向后兼容性?
  • 所以用户有旧代码的版本,您想更新到新代码?
  • 你总是遇到这种崩溃吗?如果您卸载旧代码并安装新代码会发生什么。你还遇到崩溃吗?
  • 假设用户通过无线方式获取下一个更新,他们可能会遇到此崩溃,但重启后会消失

标签: android android-intent bundle android-pendingintent classcastexception


【解决方案1】:

如果您想对已在现场(安装在用户设备上)的代码进行此类更改,则需要使您的更改向后兼容。一个例子是为X_INSTANCE_EXTRA 使用不同的键(即:更改名称),这样就不会与旧代码发生冲突。另一种方法是预期异常并验证此处返回的对象类型:

X obj = intent.getParcelableExtra(X_INSTANCE_EXTRA);

像这样:

try {
    X obj = intent.getParcelableExtra(X_INSTANCE_EXTRA);
    // Extra is the correct type, continue processing...
} catch (ClassCastException e) {
    // Not of the correct type, so this is old stuff, do something appropriate...
}

这有点难看,我通常不会这样做。当您对已经在现场的软件进行更改时,您需要考虑向后兼容性。尝试进行更改,以免旧的东西损坏。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-18
    • 2020-11-22
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    • 2012-12-08
    相关资源
    最近更新 更多