How do you pass a string from one activity to another? [duplicate]
Solution 1:
Pass values using intents.
In your first activity
Intent i= new Intent("com.example.secondActivity");
i.putExtra("key",mystring);
// for explicit intents
// Intent i= new Intent(ActivityName.this,SecondActivity.class);
// parameter 1 is the key
// parameter 2 is the value
// your value
startActivity(i);
In your second activity retrieve it.
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("key");
//get the value based on the key
}
To pass custom objects you can have a look at this link
http://www.technotalkative.com/android-send-object-from-one-activity-to-another-activity/
Solution 2:
your first activity, Activity1
public class Activity1 extends Activity {
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity1);
btn=(Button) findViewById(R.id.payBtn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent=new Intent(Activity1.this,Activity2.class);
intent.putExtra("course", "courseValue");
startActivity(intent);
}
});
}
}
Activity2
public class Activity2 extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity2);
String course=getIntent().getExtras().getString("course").toString();
Log.d("course",course);
}
}
Hope this will help you.
Solution 3:
You're on the right track - you're using an intent to launch the second activity. All you have to do is add intent.putExtra("title", stringObject);
where stringObject is the string you want to pass, and title is the name you want to give that object. You use that name to refer the object passed in the second activity as follows:
String s = (String)getIntent().getExtras().getSerializable("title");