Passing data between activities in Android Apps.

In this blog post, we will demonstrate on how to pass data between activities in an android app in Android Studio. There are many ways to communicate data to different activities in an application, but today we will be passing the data using Intents.So whats an intent ?

An Intent is a messaging object you can use to request an action from another app component. Although intents facilitate communication between components in several ways, there are three fundamental use cases: 

  • Starting an activity
  • Starting a service 
  • Delivering a broadcast
There are two types of intents :
  • Implicit Intents
  • Explicit Intents

Explicit Intents  specify which application will satisfy the intent, by supplying either the target app's package name or a fully-qualified component class name. You'll typically use an explicit intent to start a component in your own app, because you know the class name of the activity or service you want to start. For example, you might start a new activity within your app in response to a user action, or start a service to download a file in the background.

Implicit Intents do not name a specific component, but instead declare a general action to perform, which allows a component from another app to handle it. For example, if you want to show the user a location on a map, you can use an implicit intent to request that another capable app show a specified location on a map.

Now to learn how to pass data between activities, create a new android studio project and create an activity other than the main activity. This activity will be the data receiving activity. Once done, copy the following code in your activity_main.xml file :

After this, paste the following code in your MainActivity.java class:

Here we call the Intent in sendData method.The used intent is an Explicit intent . After calling the intent , we use the putExtra() method to get and send data. In our case, the data to be sent is the String from the EditText. The putExtras() methods takes in two parameters viz. a key and the value(data to be passed)

Now in the SecondActivity (the receiving activity), paste the following code in the activity_second.xml file:

To receive the data, we use the getIntent() method. Create an intent in the SecondActivity and use the getStringExtras() method since our data is a String. The getStringExtrasI() method takes in one parameter that is the key we had passed while sending the data from the MainActivity. Paste the following code in SecondActivity.class:

Output:

Comments

Popular posts from this blog

How to play Audio on Button Click in app | Android App Development | Java

Custom SeekBar in Android Studio .

How to implement simple Pie Chart in app | Android Studio | Java | Android App Development