首页 > 解决方案 > 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.

标签: androidandroid-intentandroid-activitycameraandroid-gallery

解决方案


您应该覆盖 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);
} 

推荐阅读