Android从两个类向MainActivity传字符串时TextView为空的问题
解决从Class1/Class2向MainActivity传值后TextView为空的问题
咱们先拆解下你当前代码里的核心问题:
- 你两次调用
getIntent().getExtras()拿到的其实是同一个Bundle实例——Intent里的Extra Bundle是唯一的,不会因为重复调用就生成新对象。 - 连续两次调用
name.setText()会直接覆盖内容:如果只有Class1传了值,第二次extras2.getString("nombank")会返回null,TextView就变成空;如果只有Class2传值,第一次extras.getString("nom")是null,第二次才是有效值,但要是两个都没传,结果肯定是空的。
下面给你两种实用的解决方案:
方案一:给不同来源的传值加标识区分
在Class1和Class2启动MainActivity时,额外添加一个来源标识字段,用来判断数据来自哪个类。
步骤1:Class1中启动MainActivity的代码
Intent intent = new Intent(Class1.this, MainActivity.class); intent.putExtra("source", "Class1"); // 添加来源标识 intent.putExtra("nom", "从Class1传来的字符串"); startActivity(intent);
步骤2:Class2中启动MainActivity的代码
Intent intent = new Intent(Class2.this, MainActivity.class); intent.putExtra("source", "Class2"); // 添加来源标识 intent.putExtra("nombank", "从Class2传来的字符串"); startActivity(intent);
步骤3:MainActivity中处理传值的代码
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView name = findViewById(R.id.nom); Bundle extras = getIntent().getExtras(); if (extras != null) { String source = extras.getString("source"); if ("Class1".equals(source)) { // 非空判断避免返回null导致TextView为空 String nomValue = extras.getString("nom"); name.setText(nomValue != null ? nomValue : "无Class1传值"); } else if ("Class2".equals(source)) { String nomBankValue = extras.getString("nombank"); name.setText(nomBankValue != null ? nomBankValue : "无Class2传值"); } } else { name.setText("没有任何传值"); } }
方案二:直接判断对应key是否存在(无需额外标识)
如果不想加来源标识,也可以直接检查Bundle里是否存在目标key,再进行取值:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView name = findViewById(R.id.nom); Bundle extras = getIntent().getExtras(); if (extras != null) { // 优先判断Class1的key,存在则取值 if (extras.containsKey("nom")) { name.setText(extras.getString("nom")); } // 若Class1的key不存在,再判断Class2的key else if (extras.containsKey("nombank")) { name.setText(extras.getString("nombank")); } else { name.setText("无有效传值内容"); } } else { name.setText("未收到任何传值"); } }
额外提醒
- 一定要先判断
extras是否为null,避免触发空指针异常。 - 调用
getString()时,若目标key不存在会返回null,记得加非空判断或设置默认值,防止TextView显示为空。
内容的提问来源于stack exchange,提问作者Somoud
相关产品推荐
相关产品推荐

