How to pass a value from one Activity to another in Android?


Question

I have created an Activity with a AutuCompleteTextView[ACTV] and button. I enter some text in the ACTV then press the button. After I press the button I want the Activity to go to another Activity. In the second Activity I just want to display the text entered in ACTV(of the first actvity) as a TextView.

I know how to start the second activity which is as below:

Intent i = new Intent(this, ActivityTwo.class);
startActivity(i);

I have coded this to obtain the text entered from the ACTV.

AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete);
CharSequence getrec=textView.getText();

My question here is how to pass "getrec" (after I press the button) from the first Activity to the second. And later recieve "getrec" in the second activity.

Please assume that I have created the event handler class for the button by using "onClick(View v)"

1
27
8/18/2010 9:30:25 AM

Accepted Answer

You can use Bundle to do the same in Android

Create the intent:

Intent i = new Intent(this, ActivityTwo.class);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete);
String getrec=textView.getText().toString();

//Create the bundle
Bundle bundle = new Bundle();

//Add your data to bundle
bundle.putString(“stuff”, getrec);

//Add the bundle to the intent
i.putExtras(bundle);

//Fire that second activity
startActivity(i);

Now in your second activity retrieve your data from the bundle:

//Get the bundle
Bundle bundle = getIntent().getExtras();

//Extract the data…
String stuff = bundle.getString(“stuff”); 
58
12/8/2014 6:10:52 AM

Standard way of passing data from one activity to another:

If you want to send large number of data from one activity to another activity then you can put data in a bundle and then pass it using putExtra() method.

//Create the `intent`
 Intent i = new Intent(this, ActivityTwo.class);
String one="xxxxxxxxxxxxxxx";
String two="xxxxxxxxxxxxxxxxxxxxx";
//Create the bundle
Bundle bundle = new Bundle();
//Add your data to bundle
bundle.putString(“ONE”, one);
bundle.putString(“TWO”, two);  
//Add the bundle to the intent
i.putExtras(bundle);
//Fire that second activity
startActivity(i);

otherwise you can use putExtra() directly with intent to send data and getExtra() to get data.

Intent i=new Intent(this, ActivityTwo.class);
i.putExtra("One",one);
i.putExtra("Two",two);
startActivity(i);

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon