Android开发中不同Activity之间传递String变量接收为空问题求助
问题根因
你拿到空值的核心问题出在MainActivity中输入框内容的取值时机错误:
- 你在
onCreate生命周期执行时就调用了myName = edit.getText().toString(),此时页面刚完成初始化,用户还没有在输入框输入任何内容,这里拿到的默认就是空字符串,后续点击跳转按钮时传递的也是这个提前缓存的空值,不是用户输入后的内容。
修复方案
1. 修改MainActivity的取值逻辑
把输入框内容的获取操作移动到按钮点击事件内部,确保跳转时拿到的是用户输入的最新内容,优化后代码如下:
public class MainActivity extends AppCompatActivity{ EditText edit; @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getSupportActionBar().hide(); setContentView(R.layout.activity_main); edit = findViewById(R.id.nickName); Button loginButton = findViewById(R.id.button); loginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // 点击跳转时才取输入框最新内容,加trim去除首尾空格 String myName = edit.getText().toString().trim(); // 可选:增加空输入校验,避免无意义跳转 if (myName.isEmpty()) { Toast.makeText(MainActivity.this, "请先输入昵称", Toast.LENGTH_SHORT).show(); return; } Intent i = new Intent(MainActivity.this, activity_matching.class); i.putExtra("myName", myName); startActivity(i); } }); } }
2. 可选优化:activity_matching增加空值校验
为了避免后续出现空指针异常,建议在读取传递参数后先做非空判断:
public void onBtnClick(View v) { TextView txtHello = findViewById(R.id.txtMessage); Intent b = getIntent(); myName = b.getStringExtra("myName"); // 非空校验 if (myName == null || myName.isEmpty()) { Snackbar.make(v, "未获取到用户信息", Snackbar.LENGTH_SHORT).show(); return; } // 原有逻辑不变 String swipeLeft = "Swipe (a destra o sinistra) per l'argomento di discussione"; Snackbar doSwipe = Snackbar.make(v, swipeLeft, 6000); Random rand = new Random(System.currentTimeMillis()); names = new String[]{"Name1", "Name2", "Name3", "Name4", "Name5", "Name6", "Name7", "Name8", "Name9", "Name10", "Name11", "Name12", "Name13", "Name14", "Name15", "Name16", "Name17"}; re: { s = rand.nextInt(names.length); if (myName.equals(names[s])) break re; txtHello.setText(myName + " vai a parlare con " + names[s] + "!"); doSwipe.show(); } }
内容的提问来源于stack exchange,提问作者CommuBoi
相关产品推荐
相关产品推荐

