Can someone please tell me how exactly to use getExtra()
and putExtra()
for intents? Actually I have a string variable, say str, which stores some string data. Now, I want to send this data from one activity to another activity.
Intent i = new Intent(FirstScreen.this, SecondScreen.class);
String keyIdentifer = null;
i.putExtra(strName, keyIdentifer );
and then in the SecondScreen.java
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.table);
TextView userName = (TextView)findViewById(R.id.userName);
Bundle bundle = getIntent().getExtras();
if(bundle.getString("strName")!= null)
{
//TODO here get the string stored in the string variable and do
// setText() on userName
}
}
I know it is very basic question but unfortunately I am stuck here. Please help.
Thanks,
Edit: Here the string which I am trying to pass from one screen to the other is dynamic.
That is I have an editText where I am getting string whatever user types. Then with the help of myEditText.getText().toString()
. I am getting the entered value as a string then I have to pass this data.
Push Data
The above code might be inside the main
activity
. "MyActivity.class
" is the secondActivity
we want to launch; it must be explicitly included in yourAndroidManifest.xml
file.Pull Data
In this example, the above code would be inside your
MyActivity.java
file.Gotchas
This method can only pass
strings
. So let's say you need to pass anArrayList
to yourListActivity
; a possible workaround is to pass a comma-separated-string and then split it on the other side.Alternative Solutions
Use
SharedPreferences
Put String in Intent Object
NextAcitvity in onCreate method get String
that is easy and short method
put function
Best Method...
SendingActivity
RecievingActivity
/// shortest way to recieve data..
//This requires api 12. //the second parameter is optional . If keyName is null then use the
defaultkey
as data.A small addendum: you do not have to create your own name for the key, android provides these, f.ex.
Intent.EXTRA_TEXT
. Modifying the accepted answer:Simple, In first Activity-
In second Activity-