【问题标题】:getIntent().getExtra() returns nullgetIntent().getExtra() 返回 null
【发布时间】:2017-01-20 09:55:39
【问题描述】:

我有代码可以将用户从底部栏引导到个人资料页面。

private void startNewIntent(Class className, String uid){
    Intent intent = new Intent(act, className);
    intent.putExtra("uid", uid);
    act.startActivity(intent);
    act.finish();
}

className = DisplayProfile.class;
if(FirebaseAuth.getInstance().getCurrentUser() != null){
    String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
    startNewIntent(DisplayProfile.class, uid);
} else {
    startNewIntent(EmailPasswordActivity.class);
}

在 ProfileActivity.java 中

protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    String uid = getIntent().getStringExtra("uid");
    if(uid != null){
        ...
    }
}

我也尝试使用Bundle = getIntent().getExtra() 获得相同的结果。我见过类似的问题。好像是这样:getIntent() Extras always NULL

我试过了

intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);

getIntent().getExtra != null 仍然是假的。

感谢您的帮助和建议。

编辑:为 startNewIntent() 添加上下文

【问题讨论】:

  • 可能没关系,但act是什么?
  • 活动行为我猜?
  • getIntent() 是 null 还是只是 getExtra() ??
  • act 是将启动 ProfileActivity 的当前活动。我检查了 getIntent() 不为空,它似乎是正确的 Intent。
  • 显示你如何调用startNewIntent方法

标签: android android-intent android-activity


【解决方案1】:

而不是签入 onCreate() 签入 onNewIntent():

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        String uid = getIntent().getStringExtra("uid");
        if(uid != null){
            ...
        }
    }
    
    @Override
    protected void onNewIntent(Intent intent){
        super.onNewIntent(intent);
        String uid = getIntent().getStringExtra("uid");
        if(uid != null){
            ...
        }
    }

如果它出现在 onNewIntent() 中,这意味着您正在使用 launchMode 进行活动。这就是启动模式的行为。

【讨论】:

  • 你能给我解释一下launchMode吗?谢谢
  • 在android的activity中,activity的启动方式有四种。标准,singleTop,singleTask,singleInstance。这四个用于通过堆栈管理来管理活动流。更多详情请关注 android:launchMode:link
  • 返回MainActivity并从onResume()调用getExtra()时出现同样的问题。这个变体解决了这个问题。
  • 我在更新到compileSdkVersion 30后不得不这样使用。之前总是直接在onCreate工作......我不知道这里发生了什么。
  • @ThalisVilela 这不是由于 compileSdkVersion 30 或任何其他原因,只需检查您的 AndroidManifest.xml 是否添加到该特定活动标签的启动模式?可能是您正在使用任何导致此原因的意图标志启动活动
【解决方案2】:

如果您的班级名称中已经存在".class",请避免使用。

public void startNewIntent(Class className, String uid){
Intent intent = new Intent(act.this, className+".class");
intent.putExtra("uid", uid);
startActivity(intent);
}

下一阶段

@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
String uid = getIntent().getExtras().getString("uid");
if(uid != null){
    ...
 }
}

【讨论】:

  • 我们为什么要检查 null 条件?我们在那里保留了“uid”值
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多