How to Pass Data from One Activity to Another in Android
នៅក្នុងមេរៀននេះ អ្នកនឹងរៀនបញ្ជូនទិន្នន័យពីសកម្មភាព(activity )មួយទៅសកម្មភាព(activity )មួយទៀតនៅក្នុងប្រព័ន្ធប្រតិបត្តិការ Android ដោយមិនប្រើ intent។
Basically we can send data between activities in two ways.
- Using Intent
- Using Global Variables
Below I have discussed both the methods in detail.
Note: There are some other ways like shared preferences and database (sqlite) but here I have shared only those ways that don’t involve saving of data.
Method 1: Using Intent
We can send data while calling one activity from another activity using intent. All we have to do is add the data to Intent object using putExtra() method. The data is passed in key value pair. The value can be of types like int, float, long, string, etc.
Sending Data
Here I am sending just one value, in the same way you can attach more values by using putExtra() method.
Retrieving Data
If the data sent is of type string then it can be fetched in following way.
There are several other methods like getIntExtra(), getFloatExtra(), etc to fetch other types of data.
Below is the example of passing data between activities using intents.
Example
In this example a message is passed from first activity to second when a button is pressed.
activity_first.xml
activity_second.xml
First.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | package com.androidexample; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; public class First extends AppCompatActivity { EditText textBox; Button passButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_first); textBox = (EditText)findViewById(R.id.textBox); passButton = (Button)findViewById(R.id.passButton); passButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String str = textBox.getText().toString(); Intent intent = new Intent(getApplicationContext(), Second.class); intent.putExtra("message", str); startActivity(intent); } }); } } |
Second.java
Screenshots
Method 2: Using Global Variables
We can declare a global variable in a separate class. To make it global just declare it as public static. This will allow us to directly access the variable anywhere in our application using its class name.
Just assign the value that you want to pass in global variable inside source activity and fetch it in destination activity by accessing the global variable.
Below example shows how to do this.
Example
The code for activity_first.xml and activity_second.xml will be same as above example.
DemoClass.java
First.java
Second.java
Comment below if you have doubts or know any other way to pass data from one activity to another in android.