Android studio button to new activity using bundle
Here's a step-by-step guide on how to create a button in Android Studio that starts a new activity using a Bundle:
Step 1: Create a new activity
In your Android project, go to File
> New
> Activity
> Empty Activity
. Name your activity, for example, SecondActivity
.
Step 2: Create a Bundle
In your SecondActivity
, create a Bundle object to pass data from the first activity:
Bundle bundle = new Bundle();
bundle.putString("key", "value");
Step 3: Create an Intent
In your SecondActivity
, create an Intent object to start the activity:
Intent intent = new Intent(this, SecondActivity.class);
Step 4: Put the Bundle in the Intent
Add the Bundle to the Intent using the putExtras()
method:
intent.putExtras(bundle);
Step 5: Start the activity
Start the activity using the startActivity()
method:
startActivity(intent);
Step 6: Receive the Bundle in the second activity
In your SecondActivity
, retrieve the Bundle using the getIntent()
method:
Bundle bundle = getIntent().getExtras();
Step 7: Access the data in the Bundle
Access the data in the Bundle using the getString()
method:
String value = bundle.getString("key");
Putting it all together
Here's the complete code for the button click listener in your first activity:
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getBaseContext(), SecondActivity.class);
Bundle bundle = new Bundle();
bundle.putString("key", "value");
intent.putExtras(bundle);
startActivity(intent);
}
});
And here's the complete code for the SecondActivity
:
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Bundle bundle = getIntent().getExtras();
String value = bundle.getString("key");
// Do something with the value
}
}
That's it! When you click the button, the SecondActivity
will be started with the Bundle containing the data.