【问题标题】:Why can't I get the extra that I put on my main activity [closed]为什么我不能在我的主要活动中得到额外的东西[关闭]
【发布时间】:2021-04-23 04:35:02
【问题描述】:

我在我的主要活动中添加了额外的代码,如下所示:

Intent intent = new Intent();
intent.setClass(ItemMainActivity.this, (Class<?>) map.get("itemActivity"));
intent.putExtra("user",user);
intent.putExtra("userID",userID);
startActivity(intent);

当我尝试使用此代码获取额外内容时,它返回 null:

Intent intent = this.getIntent();
Bundle extras = intent.getExtras();
String user = null, userID = null;
if (extras != null) {
    user = extras.getString("user");
    userID = extras.getString("userID");
}
Toast.makeText(getApplicationContext(),"user: "+user+" id: "+userID,Toast.LENGTH_LONG).show();

我该如何解决这个问题?

【问题讨论】:

  • 应该可以。您确定它是正确的实例并且您没有将其设置为空吗?请给出定义user 和userID 的minimal reproducible example。

标签: java android android-intent


【解决方案1】:

我想建议另一种方式.... 通用类的概念。 并创建一个您需要的数据类型的公共静态变量,并在活动中设置值并在您需要的任何地方访问它。

Public class Common{
    Public static String userId ="";
      }

在这个变量中设置值Common.userId = "YOUR_VALUE" 需要访问的时候就用Common.userId

如有不清楚之处,请随时询问。

【讨论】:

  • 它有效,谢谢,我是这样设计的:1. 我在登录时添加了额外内容 2. 在主要活动中获得额外内容 3. 我创建了新课程作为从我的主要活动中获取额外内容的会话活动不好吗?谢谢你的帮助..
  • 这很危险,因为如果系统在后台杀死应用程序,则不会设置,而额外设置。只有当用户在应用之间切换时才会发生微妙的崩溃。
猜你喜欢
  • 2017-11-27
  • 1970-01-01
  • 1970-01-01
  • 2013-08-30
  • 2010-11-12
  • 2013-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多