eBoody
eBoody

Reputation: 171

Android: with respect to Intents, Why do setType() and setData() nullify each other?

I answered this question about why setType() and setData() dont work together. I still cannot find any reason as to why. The logic eludes me.

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.

Upvotes: 4

Views: 572

Answers (1)

iheanyi
iheanyi

Reputation: 3113

You'll need to read the source code but it is likely because of the following.

setType(), setData(), and setDataAndType() all operate on a single data field. The field actually is the composition of two fields, type and data. Where type occupies one part and data the other part. So say the field is 16bits, type the upper 8 bits, data the lower 8 bits.

setType() may do an operation like this:

field = (type & 0x0F) << 8;

As you can see, it completely overwrites field. So no matter what was there before, it now only contains type information.

setData may do an operation like this:

field = data & 0x0F;

As you can see, it too completely overwrites field.

setDataAndType() then must do something like:

field = ((type & 0x0F) << 8) || (data & 0x0F);

While it too completely overwrites field, it allows setting both data and type in one call.

As to why things are the way they are - likely one of two reasons:

  1. Backwards compatibility. setType and setData were written without anticipating someone may want to do both simultaneously (or there even being a use case for this). Sometime in the future, that requirement or use case changed. However, applications had already been writing relying on that behavior. So, to keep from breaking them, they introduced a new method rather than overloading the existing ones.
  2. It is better this way. setType() and setData() were designed deliberately to be destructive to prevent users from accidentally writing bugs that would be hard to trace down and understand. This way, someone couldn't call setType(), then specify incompatible data with setData(), have the URI work in one context down the line but fail unexpected sometime later. Instead, the interface forces users to be explicit about what they want.

Upvotes: 2

Related Questions