Android Intents - Difference between SetDataAndTyp

2019-05-17 15:24发布

So I am writing an intent that should launch the gallery to view an image passed into the intent with it's Uri. This code works fine, does exactly what I want it to do:

private Intent makeGalleryIntent(String pathToImageFile) {
    Intent mGalleryIntent = new Intent(Intent.ACTION_VIEW);
    mGalleryIntent.setDataAndType(Uri.parse("file://" + pathToImageFile), "image/*");
    return mGalleryIntent;
}

But when I tried to play with it (just trying different things out as I learn), this code either crashes on the emulator because it can't launch the camera, or just pulls up my gallery on my physical device:

private Intent makeGalleryIntent(String pathToImageFile) {
    Intent mGalleryIntent = new Intent(Intent.ACTION_VIEW);
    mGalleryIntent.setData(Uri.parse("file://" + pathToImageFile));
    mGalleryIntent.setType("image/*");
    return mGalleryIntent;
}

They both look like they should do the exact same thing. Also, is there a way I could have set all of that properly just using the Intent constructor?

1条回答
看我几分像从前
2楼-- · 2019-05-17 15:40

From the documentation: Intent Documentation

To set only the data URI, call setData(). To set only the MIME type, call setType(). If necessary, you can set both explicitly with setDataAndType().

Caution: If you want to set both the URI and MIME type, do not call setData() and setType() because they each nullify the value of the other. Always use setDataAndType() to set both URI and MIME type.

Ive never really gotten an answer as to WHY they would nullify each other..If you have an idea as to why id love to hear it!

查看更多
登录 后发表回答