android - Second intent in onClick is executed before first
问题描述
I am writing an Android application and faced the problem: I need to choose an image from the gallery and then send it to the other activity (and go to that activity). When I only have an Intent which picks an image from gallery, it's doing fine, opens the gallery, lets you pick an image and then nothing happens, fine. But when I add another Intent which goes to other activity, it ignores the first intent.
ImageButton gallery;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gallery = (ImageButton) findViewById(R.id.imageButton2);
gallery.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
goToConfirmActivity();
}
});
}
public void goToConfirmActivity(){
Intent goToConfirmIntent = new Intent(MainActivity.this, confirmActivity.class);
goToConfirmIntent.putExtra("image", uri);
startActivity(goToConfirmIntent);
}
It just goes straight to confirmActivity
without choosing a pic from the gallery. I wonder how to fix that. Thank you in advance.
解决方案
您应该覆盖 onActivityResult,这样您就可以检查用户是否实际从图库中选择了图像,或者在打开图库后只是按下了返回按钮。
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK){
Uri uri= data.getData();
goToConfirmActivity(uri);
} else {
//Some error has occurred.
}
}
你的 goToConfirmActivity 方法应该是这样的:
void goToConfirmActivity(Uri uri){
Intent goToConfirmIntent = new Intent(MainActivity.this, confirmActivity.class);
goToConfirmIntent.putExtra("image", uri);
startActivity(goToConfirmIntent);
}
推荐阅读
- javascript - React:当我卸载组件时,状态不是最新的
- reactjs - 为什么切片推送在 redux 中有效但在 concat 中无效?
- c# - 删除exe.config时程序崩溃?
- python - 我有两个数据帧 A 和 B,都有一个列时间戳。如果时间戳和(时间戳+ 15分钟)之间存在于B中,我将如何检查A的时间戳
- c++ - 即使在算术运算之后,我如何才能显示用户的实际输入?
- javascript - Spatie Browsershot 无法保存图像
- wix - 设置服务的版本不是通过 GUI,wix
- java - 异步垂直与复合未来垂直。它们有何不同?
- python-3.x - 在 GitPython 中获取文件提交时间
- mysql - 如果满足条件,则使用具有多个执行路径的条件函数