Android: When do we use getIntent ()?

I do not understand why we use the getIntent() method.

Because when we need this method, we can use the onActivityResult() method.

But with the getIntent() method, this can raise a NullPointerException .

+8
source share
4 answers

http://developer.android.com/reference/android/app/Activity.html#getIntent ()

Return the intention that triggered this operation.

If you run Activity with some data, for example by doing

 Intent intent = new Intent(context, SomeActivity.class); intent.putExtra("someKey", someData); 

you can get this data using getIntent in a new action:

 Intent intent = getIntent(); intent.getExtra("someKey") ... 

Thus, it is not for processing returned data from an Activity, such as onActivityResult, but for transferring data to a new activity.

+20
source

getInent used to transfer data from an action to another. For example, if you want to switch from an action called startActivity to another with the name endActivity and want the data from startActivity be known in endActivity , do the following:

In startActivity :

 String dataToTransmit="this info text will be valid on endActivity"; Intent intent =new Intent(this, endActivity.class); intent.putExtra("dataToTransmitKey",dataToTransmit); startActivity(intent); 

on endActivity :

 Intent intent = getIntent(); String dataTransmited=intent.getStringExtra("dataToTransmitKey"); 
+2
source
 listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(ItemListView.this, ViewItemClicked.class); String name = itemList.get(position).getString(1); String description = itemList.get(position).getString(2); String something_else = itemList.get(position).getString(3); intent.putExtra("name", name); intent.putExtra("description", description); intent.putExtra("something_else", something_else); startActivity(intent); } 

In your activity details:

 Intent intent = getIntent(); String name = intent.getStringExtra("name"); String description = intent.getStringExtra("description"); String something_else = intent.getStringExtra("something_else"); 

Now use the lines to show the values ​​in the right places: how

edittext.setText(name);

0
source

In fact, if you want to send some data from one page to another, use Get or Put Intent

.Example:

 Intent intent = new Intent(context, HomeActivity.class); intent.putExtra("yourData", yourData); 

Get data from

 Intent intent = getIntent(); intent.getExtra("yourData") 
0
source

Source: https://habr.com/ru/post/1206114/


All Articles