【问题标题】:App crashing on starting another activity with intent and .putExtra应用程序在启动另一个带有意图和 .putExtra 的活动时崩溃
【发布时间】:2023-03-31 18:07:01
【问题描述】:

我正在尝试通过 Intent 和 putExtra 打开另一个活动。 以前可以正常运行,现在崩溃了。

startActivity(new Intent(ForgotPassword.this, OtpVerification.class)
                                .putExtra("user", user)
                                .putExtra("otp", verificationId));
                        finish();

这里的用户是一个类对象,正在另一个活动中接收它

user = getIntent().getParcelableExtra("user");

该应用程序甚至没有进入另一个活动,并且在 logcat 中没有任何错误消息而崩溃。 只有当我添加 .putExtra 代码时才会发生这种情况

【问题讨论】:

    标签: android android-studio android-intent parcelable


    【解决方案1】:

    尝试按以下方式添加 putExtra

    Intent intent = new Intent(ForgotPassword.this, OtpVerification.class);
    intent.putExtra("user", user);
    intent.putExtra("otp", verificationId);
    startActivity(intent);
    finish();
    

    然后获取intent extras

    Intent intent= getIntent();
    Bundle extras = intent.getExtras();
    if(extras != null)
        String data = extras.getString("keyName");
    

    【讨论】:

      【解决方案2】:

      您的用户是您试图从一个活动传递到另一个活动的对象。 因此,您可以创建一个实现 Serializable 接口的自定义类。(您也必须能够使用 Parcelable,但我没有使用它的经验)

      //要通过: intent.putExtra("User", user);

      // 在第二个 Activity 中检索对象 getIntent().getSerializableExtra("User");

      注意点:你的主自定义类中的每个嵌套类都必须实现了 Serializable 接口 例如:

      class MainClass implements Serializable {
      
          public MainClass() {}
      
          public static class ChildClass implements Serializable {
      
              public ChildClass() {}
          }
      }
      

      参考:How to pass an object from one activity to another on Android

      【讨论】:

        【解决方案3】:

        感谢您的建议,我发现的实际问题是我的用户对象有一个名为 image(字符串类型)的变量,并且长度值约为 1,000,000(我在其中使用 base64 存储字符串编码的图像)。一旦我将大小减小到数千,它就起作用了。我不知道为什么应用程序不能跨活动发送如此大的数据。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-09-20
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多