如何在无输入数据及图片时切换Activity且避免应用崩溃?
解决无数据/图片传递时Activity切换崩溃问题
崩溃的核心原因是MainActivity未对Intent传递的数据做非空校验:当没有传递图片时,getByteArrayExtra("image")返回null,直接传入BitmapFactory.decodeByteArray()会触发空指针异常;文本参数未传递时,虽然不会崩溃,但可能显示null字样,不符合预期。
修改MainActivity代码,添加非空判断:
ImageView imageView = (ImageView) findViewById(R.id.main_image); // 处理图片数据:先判断是否存在再解码 byte[] byteArray = getIntent().getByteArrayExtra("image"); if (byteArray != null) { Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length); imageView.setImageBitmap(bitmap); } else { // 可选:设置默认占位图,比如 // imageView.setImageResource(R.drawable.default_placeholder); } text_title = (TextView) findViewById(R.id.title); String title_temp = getIntent().getStringExtra("temp1"); // 文本为空时显示空字符串或默认提示 text_title.setText(title_temp != null ? title_temp : ""); text_author = (TextView) findViewById(R.id.author); String author_temp = getIntent().getStringExtra("temp2"); text_author.setText(author_temp != null ? author_temp : "");
可选:上传Activity中新增无数据跳转逻辑
如果需要在上传页面提供“不传递数据直接跳转”的按钮,可以单独写跳转逻辑:
Button skipToMain = findViewById(R.id.skip_button); skipToMain.setOnClickListener(v -> { Intent intent = new Intent(UploadActivity.this, MainActivity.class); startActivity(intent); });
核心原则是接收方必须对所有可能为空的参数做校验,这是组件间通信的基本容错要求,能避免因数据缺失导致的崩溃。
内容的提问来源于stack exchange,提问作者Chanyoung
相关产品推荐
相关产品推荐

