getStringExtra()返回null

时间:2018-01-23 21:08:22

标签: android

我尝试通过意图向函数发送字符串的额外数据,但我收到null。

这是intent.put:

 private void takePicFromGallery(String nameOfButton) {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    **intent.putExtra(NAME_OF_BUTTON, nameOfButton.toString());**
    startActivityForResult(intent.createChooser(intent, "choose picture"), PICK_FROM_GALLERY);

以下是获取:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    String nameOfButton = data.getStringExtra(NAME_OF_BUTTON);
    switch (nameOfButton) {
        case "ibMainPicture": {
            ibMainPicture.setImageBitmap(bitmap);
            break;
        }
        case "imageButton1": {
            imageButton1.setImageBitmap(bitmap);
            break;
        }

2 个答案:

答案 0 :(得分:3)

onActivityResult期间收到的意图与您在takePicFromGallery方法中创建的意图不同。您启动的意图由打开的Activity消耗,它会将新意图发送回您的应用程序。

选项1(首选项):

private static final int IB_MAIN_PICTURE_REQUEST_CODE = 524;
private static final int IMAGE_BUTTON_1_REQUEST_CODE = 785;

private void takePicFromGallery(String nameOfButton) {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    if(nameOfButton.equals("ibMainPicture")) {
        startActivityForResult(intent.createChooser(intent, "choose picture"), IB_MAIN_PICTURE_REQUEST_CODE);
    else if(nameOfButton.equals("imageButton1") {
        startActivityForResult(intent.createChooser(intent, "choose picture"), IMAGE_BUTTON_1_REQUEST_CODE);
    }

然后在获得结果时:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(resultCode == Activity.RESULT_OK) {
        if(requestCode == IB_MAIN_PICTURE_REQUEST_CODE) {
            ibMainPicture.setImageBitmap(bitmap);
        } else if(requestCode == IMAGE_BUTTON_1_REQUEST_CODE) {
            imageButton1.setImageBitmap(bitmap);
        }
    }
}

选项2:

private static String lastButtonClicked = null;

private void takePicFromGallery(String nameOfButton) {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    lastButtonClicked = nameOfButton.toString();
    startActivityForResult(intent.createChooser(intent, "choose picture"), PICK_FROM_GALLERY);
}

然后在获得结果时:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(lastButtonClicked == null || resultCode != Activity.RESULT_OK || requestCode != PICK_FROM_GALLERY) {
        return;
    }
    switch (lastButtonClicked) {
        case "ibMainPicture": {
            ibMainPicture.setImageBitmap(bitmap);
            break;
        }
        case "imageButton1": {
            imageButton1.setImageBitmap(bitmap);
            break;
        }
        ...
}

答案 1 :(得分:0)

为每个不同的按钮点击使用特定的请求代码而不是通用的PICK_FROM_GALLERY,然后在onActivityResult中,您可以检查使用意图发送的请求代码