Salim
Salim

Reputation: 143

Getting Intent of type Image Confusion

I am currently learning Android and came across with this:

    if (intent.getType().indexOf("image/") != -1) {
    // Handle intents with image data ...
    } else if (intent.getType().equals("text/plain")) {
    // Handle intents with text ...

I don't understand why there is intent.getType().indexOf("image/")!=-1, As far as I understand it's being used to know that if the intent contains data of type Image (Correct me if wrong). but why not its used like it is used with type "text/plain". Why its using indexOf and why its checked against -1.

Pardon, if the question doesn't makes sense after all. But, as I said I am learning and didn't found much information of it anywhere.

Upvotes: 0

Views: 128

Answers (2)

MrSalmon
MrSalmon

Reputation: 89

getType will return a mimetype such as "image/png" "text/plain" "application/json" etc.

The indexOf call is to see if the string "image/" exists somewhere in the mimetype - or more practically if the type is an image. The author does not care if it is a jepg ("image/jpeg") or a png ("imgage/png") etc. just that it is an image.

The check against -1 is because if the "image/" substring is not found, that will be the return value.

if it is not an image, they are checking to see if it is plain text.

This is probably not the cleanest way to achieve this, but it gets the job done.

Upvotes: 1

CommonsWare
CommonsWare

Reputation: 1007554

My guess is that whoever wrote the code is using this to try to match anything starting with image/. Using startsWith() would be simpler and more reliable.

Upvotes: 1

Related Questions