Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why initialize the key of extra?

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:

  1. Why does the key have to be public?

  2. 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;

  3. 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.

like image 209
user2882662 Avatar asked Dec 02 '25 05:12

user2882662


1 Answers

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.

like image 97
Simon Avatar answered Dec 05 '25 04:12

Simon