Over a million developers have joined DZone.

Switching Activities in Android

DZone's Guide to

Switching Activities in Android

· Java Zone
Free Resource

Learn how our document data model can map directly to how you program your app, and native database features like secondary indexes, geospatial and text search give you full access to your data. Brought to you in partnership with MongoDB.

The following article shows how to create a new activity when the user clicks the button. 

1. Create a new activity


2. You can see new UI for 2nd activity and then we change string value as below


3. In MainActivity.java we can added below line to switch activity. (there are few ways to achieve it, this only one way)

Intent intent =new Intent(MainActivity.this,SecondActivity.class);2 startActivity(intent);


An intent is an abstract description of an operation to be performed. It can be used withstartActivity to launch an Activity, broadcastIntent to send it to any interestedBroadcastReceiver components, and startService(Intent) or bindService(Intent, ServiceConnection, int) to communicate with a background Service.

4. Just run app and see it. (click back button to go to previous activity)


Now we will try to pass message from one activity to second activity


An intent not only allows you to start another activity, but it can carry a bundle of data to the activity as well.

//passing string 
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
intent.putExtra(EXTRA_MESSAGE, name);

Then we will retrieve data

// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);


A Fragment represents a behavior or a portion of user interface in an Activity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. A fragment must always be embedded in an activity and the fragment's lifecycle is directly affected by the host activity's lifecycle. For example, when the activity is paused, so are all fragments in it, and when the activity is destroyed, so are all fragments. Android introduced fragments in Android 3.0 (API level 11).  Next post will content more about Fragment with some sample coding.

Discover when your data grows or your application performance demands increase, MongoDB Atlas allows you to scale out your deployment with an automated sharding process that ensures zero application downtime. Brought to you in partnership with MongoDB.


Published at DZone with permission of Madhuka Udantha, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}