Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to start an Intent by passing some parameters to it?

I would like to pass some variables in the constructor of my ListActivity

I start activity via this code:

startActivity(new Intent (this, viewContacts.class)); 

I would like to use similar code, but to pass two strings to the constructor. How is possible?

like image 372
Pentium10 Avatar asked Mar 08 '10 22:03

Pentium10


People also ask

What are the parameters of intent?

Intent parameters are used to identify and extract values within training phrases. These are specific words or phrases you want to collect from the user. Parameter name: The name associated with the parameter. This is used to reference the parameter in slot filling for scenes.

How do you initialize an intent?

You can start a new instance of an Activity by passing an Intent to startActivity(). The Intent describes the activity to start and carries any necessary data. If you want to receive a result from the activity when it finishes, call startActivityForResult().

How do you pass data from one activity to another activity using intent?

Using Intents This example demonstrate about How to send data from one activity to another in Android using intent. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.


2 Answers

In order to pass the parameters you create new intent and put a parameter map:

Intent myIntent = new Intent(this, NewActivityClassName.class); myIntent.putExtra("firstKeyName","FirstKeyValue"); myIntent.putExtra("secondKeyName","SecondKeyValue"); startActivity(myIntent); 

In order to get the parameters values inside the started activity, you must call the get[type]Extra() on the same intent:

// getIntent() is a method from the started activity Intent myIntent = getIntent(); // gets the previously created intent String firstKeyName = myIntent.getStringExtra("firstKeyName"); // will return "FirstKeyValue" String secondKeyName= myIntent.getStringExtra("secondKeyName"); // will return "SecondKeyValue" 

If your parameters are ints you would use getIntExtra() instead etc. Now you can use your parameters like you normally would.

like image 73
Xitcod13 Avatar answered Nov 15 '22 12:11

Xitcod13


I think you want something like this:

Intent foo = new Intent(this, viewContacts.class); foo.putExtra("myFirstKey", "myFirstValue"); foo.putExtra("mySecondKey", "mySecondValue"); startActivity(foo); 

or you can combine them into a bundle first. Corresponding getExtra() routines exist for the other side. See the intent topic in the dev guide for more information.

like image 33
RickNotFred Avatar answered Nov 15 '22 11:11

RickNotFred