Android Development - How to switch between two Activities


If you are new to Android App Development and understand how an Activity works, the next thing that will come to your mind is "How to switch from one Activity to another based on an action - such as button click?"

Let's see a code example of how you can do that!

Let's say you have created a second activity with the name MySecondActivity.java, to open this activity you would need to add the blow line of code on your method where the action is performed,

Intent indent = new Intent(getApplicationContext(), MySecondActivity.class);
startActivity(indent);
How to pass data from one Activity to another?

Now that you know how to call one activity from another using Indent, let's see how we can pass data just like we can do using an HTTP GET/Post request,

Intent indent = new Intent(getApplicationContext(), MySecondActivity.class);

indent.putExtra("key","value");
indent.putExtra("key1,"value1");

startActivity(indent);
How to read the data from one Activity to another?

Now that we know how to send data from one activity to other, let's see how the other activity can read that passed data!

Intent intent = getIntent();
String data = indent.getStringExtra("key");
String data1 = indent.getStringExtra("key1");
startActivity(indent);

Related post: https://code2care.org/q/pass-data-between-two-activities-intent

How to switch between two Activities
How to switch between two Activities


Have Questions? Post them here!



Recent Posts:




Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and Software Developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include Learnings, Video Tutorials, Code Snippets, How Tos, Blogs, Articles, etc.