Android多Intent跳转同页时Create Recipe按钮崩溃解决方法
问题修复方案
你当前Cancel按钮跳转正常,说明afterCancel页面已在清单文件注册、基础跳转链路没有问题,崩溃完全来自Create Recipe分支独有的逻辑错误,按以下点排查修复即可:
- 空校验逻辑写反
现有判断条件if (isEmpty(etRecipeName, etDuration, etIngredient, etDesc) == false)逻辑完全颠倒:- 所有输入框已填写时,
isEmpty()返回false,会错误触发「存在空字段」的提示,不会进入创建流程 - 存在空输入框时,
isEmpty()返回true,反而进入else分支调用createRecipe(),此时传入的空内容会触发空指针、格式转换异常(比如时长输入框内容转整数失败)直接导致崩溃
直接把判断条件改成如下即可:
if (isEmpty(etRecipeName, etDuration, etIngredient, etDesc)) { Toast.makeText(MainActivity.this, "There are empty fields. Please fill up all fields", Toast.LENGTH_SHORT).show(); return; // 校验不通过直接返回,不执行后续逻辑 } // 校验通过再走创建、跳转逻辑 - 所有输入框已填写时,
- 首页Intent调用的问题
你提到首页仅调用了this.getintent(),Android系统的API是大小写敏感的,正确获取启动Intent的方法为this.getIntent()(Intent首字母I大写),如果是自定义的getintent()方法,需要注意:
你当前Create按钮跳转使用的Intent和Cancel按钮完全一致,没有携带任何新创建的食谱参数,如果自定义方法内部默认要读取Intent中的食谱数据,会因为取到null触发空指针崩溃。如果需要把新创建的食谱传给首页,要在跳转前把数据塞进Intent,同时首页取数据前先判空:
首页取数据逻辑:// 创建食谱后把数据传入Intent Recipe newRecipe = createRecipe(etRecipeName, etDuration, etIngredient, etDesc); Toast.makeText(MainActivity.this, "Recipe Created", Toast.LENGTH_SHORT).show(); Intent changePage = new Intent(MainActivity.this, afterCancel.class); changePage.putExtra("extra_recipe", newRecipe); // Recipe类需要实现Serializable/Parcelable接口 startActivity(changePage);Intent intent = getIntent(); if (intent != null) { Recipe recipe = (Recipe) intent.getSerializableExtra("extra_recipe"); if (recipe != null) { // 处理新创建的食谱数据 } }
内容的提问来源于stack exchange,提问作者Kelven Lim
相关产品推荐
相关产品推荐

