When we want an intent to carry some data to another application component, we use an extra of that intent. An intent is simply a key value pair. We first define our key as a public constant, and give it a value. e.g.
public static final String extra_key = "com.example.myapp.MESSAGE";
We also have to assign the key the data which needs to be carried by the intent. e.g.
String extra_value = editText.getText().toString();
Then we make an extra of the intent like:
intent.putExtra(extra_key, extra_value);
MY QUESTIONS:
Why does the key have to be public?
Why do we need to intialize the key in the first place, why can't we just declare it, because it will be assigned a value (the data to
be carried by the intent) anyway. So why couldn't we do something
like public static final String extra_key;
I have read that the key value should include the reverse domain name so that it is unique in case other packages plunge in. But what is the point of giving it a unique value when it will anyway be assigned another value which is the data to be carried by the intent.
Thank you in advance.
Why does the key have to be public?
It doesn't. This is not a question about intent extras or key value pairs. It is simply a question about Java variable scope and visibility.
In calling class:
intent.putExtra("KEY_NAME", "Key_Value");
In receiving component:
intent.getStringExtra("KEY_NAME");
This work just fine. Good practice is to make it public final static so that the sender and receiver can use the same constant name.
Why do we need to intialize the key in the first place, why can't we just declare it, because it will be assigned a value (the data to be carried by the intent) anyway. So why couldn't we do something like
See above. The key name is nothing more than a string. The key does not carry the data, the value does.
I have read that the key value should include the reverse domain name.
This makes no sense. The key value is whatever data the sender wants to send to the receiver. Or did you mean the key name? The name of the key must be know by the receiver so if this intent is to start an external component, then you must use the key name as defined by the receiver. If the intent is for an internal component, then you define the name to be whatever you want. I can see no good reason to include the package name. It just uses more memory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With