Communicating between Activities


An Activity is a single screen that a user can interact with. There can be multiple activities in an App.
 So, in this tutorial, I will show you how to move from one another to another activity.
Intent is used to communicate between activities; to link up two activities, you need Intent. 
Intents is not limited to communicating between activities, you can also use Intent to communicate between Android components.

There are two types of Intents.
Explicit Intent: It is used when we want to communicate between activities.
Implicit Intent: It is used when we want to communicate between Android components.
 
In this tutorial, we will be making use of an explicit intent.
Steps:

  1. Create a new Android Project. 
  2. Create another activity besides the one you have. 
  3. Modify your activity_main.xml by adding a button 
  4. Modify your MainActivity.java by writing the logic responsible for linking activities. 
  5. Modify your activity_main2.xml to differentiate it from the first activity
 
By now, you have been used to creating new Android project, if not, check out this link
 Getting familiar with Android Studio
 
The second step, go to left side of your Android Studio, under your java folder, Right click on the first package.
 Go to New > Activity > Empty Activity > Finish.

 

Step three: Go to your activity_main.xml and create a button. When the button is clicked, it will take us to the next Activity.

<!--Text to differentiate between the two activities-->
<TextView
   
android:layout_width="wrap_content"
    android:layout_height="wrap_content"
   
android:text="First Activity"
   
android:textSize="50sp"/>
<!--Button to take us to the next activity-->
<Button
   
android:layout_width="wrap_content"
   
android:layout_height="wrap_content"
   
android:text="Next"
   
android:onClick="next"
   
android:textSize="30sp"/>
 
Step four: Go to your MainActivity.java and write logics
 
//Create an onClick listener method
//Create the intent that links the two activities
//@this means the current activity we are, i.e. the first activity
//@Main@Activity.class means the next activity we want to go when the next button is clicked
//@startActivity(activityIntent); starts the new activity
public void next (View view){
    Intent activityIntent =
new Intent(this, Main2Activity.class);
    startActivity(activityIntent);
}
 
Step five: Go to your activity_main2.xml or whatever name you gave to the new activity you created and modify it by adding a TextView.

<TextView
   
android:layout_width="wrap_content"
   
android:layout_height="wrap_content"
   
android:text="This is the Second Activity"
   
android:textSize="50sp"/>