Android transfer data between activity

Passing data between Activities using Intent in Android

Jul 3, 2019 · 5 min read

In this tutorial, we will learn how to use Intent and then we will pass the data using Intent from one activity to another.

Through Intent we can move from one activity to another activity and Intent can also be used to pass the data from one activity to another activity.

In the previous article, we designed the Login Page and now we will learn how to use Intent to pass data from LoginActivity to the next activity.

First of all, we h ave to link the views of activity_login.xml with LoginActivity In activity_login.xml, we have used two EditTexts and one button. Lets initialize them in our LoginActivity.

EditText edittextfullname,edittextusername; : This is the way to define the views which we have used in the layout and you can give any name you want. Here we have given edittextfullname and edittextusername.

Button loginbutton; : Here we have defined a button with name loginbutton.

Now lets link the views using findViewById in LoginActivity.

edittextfullname=findViewById(R.id.editTextFullName); : This line help to find the id by findViewById method and the id which we have given for widget in l ayout XML file.

edittextusername=findViewById(R.id.editTextUserName); : This line does the same thing as edittextfullname does.

loginbutton=findViewById(R.id.LoginButton);:This line does the same thing as edittextfullname and edittextusername does.

We have successfully linked the views defined in the activity_login with LoginActivity.

Now we have to create a new activity so let’s create an activity with the same procedure we have gone through in the previous article.

Источник

Android | How to send data from one activity to second activity

This article aims to tell and show about how to “Send the data from one activity to second activity using Intent”. In this Example, we have two activities, activity_first which is the source activity and activity_second which is the destination activity. We can send the data using putExtra() method from one activity and get the data from the second activity using getStringExtra() methods.

Example:

In this Example, one EditText is used to input the text. This text is sent to the second activity when the “Send” button is clicked. For this, Intent will start and the following methods will run:

  • putExtra() method is used for send the data, data in key value pair key is variable name and value can be Int, String, Float etc.
  • getStringExtra() method is for getting the data(key) which is send by above method. according the data type of value there are other methods like getIntExtra(), getFloatExtra()

How to create an Android App to send and receive the data between two activity

Step 1: Firstly create a new Android Application. This will create an XML file and a Java File. Please refer the pre-requisites to learn more about this step.

Step 2: Open “activity_first_activity.xml” file and add the following widgets in a Relative Layout:

  • A EditText to Input the message
  • A Button to send the data

Also, Assign the ID to each component along with other attributes as shown in the image and the code below. The assigned ID on a component helps that component to be easily found and used in the Java files.

Syntax:

Here the given IDs are as follows:

  • Send Button: send_button_id
  • input EditText: send_text_id

This will make the UI of the Application.

Step 3: Now, after the UI, this step will create the Backend of the App. For this, open the “first_activity.java” file and instantiate the components made in the XML file (EditText, send Button) using findViewById() method. This method binds the created object to the UI Components with the help of the assigned ID.

Читайте также:  Android hs usb qdloader 9008

General Syntax:

ComponentType object = (ComponentType)findViewById(R.id.IdOfTheComponent);

Syntax for components used:

Button send_button= (Button)findViewById(R.id.send_button_id);
send_text = (EditText) findViewById(R.id.send_text_id);

Step 4: This step involves setting up the operations on the sending and received the data. These operations are as follows:

1. first Add the listener on the send button and this button will send the data. This is done as follows:

send_button.setOnClickListener(new View.OnClickListener() <>

after clicked this button following operation will be performed.

2. Now create the String type variable for store the value of EditText which is input by user. Get the value and convert it to string. This is done as follows:

String str = send_text.getText().toString();

3. Now create the Intent object First_activity.java class to Second_activity class. This is done as follows:

Intent intent = new Intent(getApplicationContext(), Second_activity.class);

where getApplicationContext() will fetch the current activity.

4. Put the value in putExtra method in key value pair then start the activity. This is done as follows:

intent.putExtra(“message_key”, str);
startActivity(intent);

where “str” is the string value and the key is “message_key” this key will use to get the str value

Step 5: Now we have to create a Second_Activity to receive the data.
The steps to create the second activity is as follows:

android project > File > new > Activity > Empty Activity

Step 6: Now open your second xml file.
Add TextView for display the receive messages. assign ID to Textview. Second Activity is shown below:

Step 7: Now, open up your second activity java file and perform the following operation.

1. Define the TextView variable, use findViewById() to get the TextView as shown above.

receiver_msg = (TextView) findViewById(R.id.received_value_id);

2. Now In second_activity.java file create the object of getTntent to receive the value in String type variable by getStringExtra method using message_key.

Intent intent = getIntent();
String str = intent.getStringExtra(“message_key”);

3. The received value set in the TextView object of the second activity xml file

Step 8: Now Run the app and operate as follows:

  • When the app is opened, it displays a “Input” EditText. Enter the value for the send.
  • click the send button then message will display on second screen.

Below is the complete code for the Application.

Источник

Transfer Data between Activities with Android Parcelable

An Android app typically consists of more than one activity that need to pass data between each other. For example a primary activity with a list of elements and a corresponding secondary activity to show the details of these elements. To move from one activity to another you use the intent class to connect them together. This lets you launch an activity and optionally return later (If you’re new to intents there’s a good resource in the Google dev docs that explains the process)

Part of the process is sending data between activities and you do that via the putExtra and getExtra methods of our intent object. The idea is to make the process of passing different types of data easy as:

This works well for basic data types such as string , bool , and Integer but doesn’t work for objects. What should you do when you want to pass an object and its data from one activity to the other? You use the parcelable interface

Introducing the Parcelable Interface

Since objects can contain any number of mixed data types you can’t use putExtra to move values across. Java has had the ability to serialize objects for a while, but it’s a slow process as the system needs to perform heavy lifting to move the data. Parcelable is an Android only Interface used to serialize a class so its properties can be transferred from one activity to another.

Implementing Parcelable

The Parcelable interface adds methods to all classes you want to be able to transfer between activities. These methods are how parcelable deconstructs the object in one activity and reconstructs it in another.

For this example you’ll look at how to implement parcelable in a simple class. I used this class in one of my previous articles where I created a property listing and a corresponding detail activity. The idea is that when you select a property in the list view you’re taken to an expanded detail view to find out more info.

Creating the Property Class

First create a class to hold info about each property. Start by adding the following into a new class file in your project.

The class contains a series of properties, getter functions and a constructor to create a single object of the class.

Add the Parcelable Interface

Here’s the main part, implementing the interface. Change the declaration of the class as follows:

Add the following methods inside the class. I’ll run through how they work shortly.

Читайте также:  Угадай картинку для андроида

Parcelable needs this code to function. It handles the process of copying your object data into a parcel for transmission between activities and then re-creating the object on the other side.

Let’s break down how this all works.

Writing Method – writeToParcel

In this method you add all your class properties to the parcel in preparation for transfer. You use each of the write methods to add each of your properties.

Notes:

  • The order in which you write these values is important. When collecting these values later you will need to collect them in the same order.
  • If you’re going to send boolean values (for example the featured property). You will have to use writeValue and then force cast it to a boolean on the other side as there is no native method for adding booleans.

Reading Method – Property

This method is the constructor, called on the receiving activity, where you will be collecting values.

When the secondary activity calls the getParcelableExtra method of the intent object to start the process. This constructor is where you collect the values and set up the properties of the object:

At this point you’ve populated the object with data.

If you are using your own object then the name of this function will match the name of your own class e.g person , animal , place , the name has to match the class name.

The Creator Method

Parcelable requires this method to bind everything together. There’s little you need to do here as the createFromParcel method will return your newly populated object.

Other methods – describeContents

This method doesn’t do much.

Starting the Intent in the First Activity

Inside the first activity create your intent object and use the putExtra method to add the whole class as an extra. This will only work if you’ve implemented the Parcelable interface correctly (as it’s at this point parcelable starts serializing your object).

If this works, the new activity will open. You will need to ensure the activity is added to your manifest file.

Collecting Values in the Secondary Activity

Now that you’re in the second activity you need to collect the intent object and extract the property class that’s been converted into a parcel . Once you’ve done this you can call the standard methods to get the data like property name, price and description.

Pass the Parcel

As you have see, there’s work involved in getting parcelable up and running, but once it all works the payoff is worth it.

You can move entire objects from one activity to another, retaining all class methods and abilities. This is great if you have a complex method that transforms your data.

You no longer have to remember the different names which you would normally pass to the intent object as extra data, e.g String streetName = intent.getStringExtra(«streetName»); . You can get your object and move on.

The process is fast and optimized. Doing it this way is faster than using Java’s serialize functionality as you implicitly tell it how to save and extract your data.

Please let me know if you have any comments or questions.

Источник

Passing Data Between Activities Android Tutorial

When you develop an android application, you always need to pass data between activities. And even more, you sometimes need to pass data between all activities for example pass session-id, user-name, and password. In this article, I will tell you how to use android Intent or Application object to pass data between activities.

1. Pass Data Between Activities Overview.

  1. There are two activities in this example, a Source Activity, and a Target Activity.
  2. The Source Activity contains two buttons ( PASS DATA TO NEXT ACTIVITY and PASS DATA TO NEXT ACTIVITY AND GET RESULT BACK ).
  3. The Target Activity contains one button ( PASS RESULT DATA BACK TO SOURCE ACTIVITY ).
  4. If you click the first button in the Source Activity, it will pass data to the Target Activity, and when you click the return button in the Target Activity, the Source Activity can not get the response data from Target Activity. See the video demo from https://youtu.be/SKjZblBXoik.
  5. If you click the second button in the Source Activity, it will pass data to the Target Activity also, and when you click the return button or click the android Back menu at the bottom in the Target Activity, the Source Activity can get the Target Activity returned response result data and display the result text in the Source Activity. See the video demon from https://youtu.be/4_cBFxwtc50.

2. Pass Data Between Activities Use Intent Object.

  1. Create an instance of android.content.Intent class, pass the Source Activity object ( who sent the intent object ) and the Target Activity class ( who can receive the intent object ) to the Intent class constructor.
  2. Invoke the above intent object’s putExtra(String key, Object data) method to store the data that will pass to Target Activity in it.
  3. Invoke Source Activity object’s startActivity(intent) method to pass the intent object to the android os.
  4. In the Target Activity, call getIntent() method to get the Source Activity sent intent object.
  5. In the Target Activity, call the above intent object’s getStringExtra(String key) to get Source Activity passed data. The key should be the same as step 2 when invoking the intent object’s putExtra method.
Читайте также:  Эпл айди вход с андроида

3. Pass Data Back From Target Activity.

  1. Create a New Explicit or Implicit android.content.Intent class’s instance in the Source Activity.
  2. Store the passed data in the above intent object by invoking its putExtra(String key, Object data) method, the key is a message key, the data is the passed data value.
  3. If you want to get the response data from the Target Activity, now you should call startActivityForResult(Intent intent, int requestCode) method in the Source Activity, this method will pass the intent object to android os and wait for the response from the Target Activity. The first parameter is the intent object, the second parameter is a user-defined integer number that is used to check whether the returned intent object is related to this request.
  4. To return data back to Source Activity from the Target Activity, you should create an instance of android.content.Intent class in the Target Activity. Do not need to provide constructor parameters at this time.
  5. Call above intent object’s putExtra(String key, Object data) method to set the returned result data in the intent object.
  6. Call setResult(RESULT_OK, intent) method in the Target Activity to set the returned intent in android os. The first parameter can be android.app.Activity.RESULT_OK or RESULT_CANCELED, the second parameter is the intent object.
  7. In the Source Activity java class, override onActivityResult(int requestCode, int resultCode, Intent dataIntent) method, the requestCode is just the user-defined integer number that is passed in above startActivityForResult method, use the requestCode to check which startActivityForResult request can use the returned dataIntent object if there are multiple places invoke the startActivityForResult method in the Source Activity. The resultCode value shows whether the request is ok or canceled.

4. Pass Data Between Activities Example Source Code.

4.1 Source Activity Layout Xml File.

4.2 Source Activity Java Code.

4.3 Target Activity Layout Xml File.

4.4 Target Activity Java Code.

Users can go back to source activity by two methods.

  1. Click the return button in the target activity. There is java code that listens to the return Button click event.
  2. Type back menu in android device. You should override Activity.onBackPressed() method to process this event.

5. How To Share Data Between Multiple Activities.

  1. A reader comments that he has multiple activities, each activity want to set some data in somewhere, and when all the activities set data finished, the last activity will send all the activities saved data to a database, how to implement this?
  2. There are 2 methods to share data between activities.1. Share data in memory. 2. Share data in a local file. When your last activity wants to save the data to the database, it can either read the data from memory or a local file then save the data to the database.
  3. To share data in memory, you can use the android application singleton, you should create your own android java class that extends the android.app.Application class. Then your android application instance will be created when the android app startup. Below is the source code of your own android application class.

Now in each activity, you can run the code MyOwnApplication app = MyOwnApplication.getApplicationContext(); to get the application object, then call the app.setData(data) method to set the share data.

In the last activity which you want to save the data to a database, you can run the code MyOwnApplication app = MyOwnApplication.getApplicationContext(); to get the application object, and then call the code app.getData() to get the data saved by multiple activities. Now you can save the shared data into a database.

  • You can read the article Android Get Application Context From Anywhere Example to learn more about how to use android application context to share data.
  • The other way is to save the shared data in a local file, you can read the article Android Shared Preferences Example, Android Sharedpreferences Save/Load Java Object Example to learn more.
  • Источник

    Оцените статью