Related
How can I send data from one activity (intent) to another?
I use this code to send data:
Intent i=new Intent(context,SendMessage.class);
i.putExtra("id", user.getUserAccountId()+"");
i.putExtra("name", user.getUserFullName());
context.startActivity(i);
First, get the intent which has started your activity using the getIntent() method:
Intent intent = getIntent();
If your extra data is represented as strings, then you can use intent.getStringExtra(String name) method. In your case:
String id = intent.getStringExtra("id");
String name = intent.getStringExtra("name");
In the receiving activity
Bundle extras = getIntent().getExtras();
String userName;
if (extras != null) {
userName = extras.getString("name");
// and get whatever type user account id is
}
// How to send value using intent from one class to another class
// class A(which will send data)
Intent theIntent = new Intent(this, B.class);
theIntent.putExtra("name", john);
startActivity(theIntent);
// How to get these values in another class
// Class B
Intent i= getIntent();
i.getStringExtra("name");
// if you log here i than you will get the value of i i.e. john
Add-up
Set Data
String value = "Hello World!";
Intent intent = new Intent(getApplicationContext(), NewActivity.class);
intent.putExtra("sample_name", value);
startActivity(intent);
Get Data
String value;
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
value = bundle.getString("sample_name");
}
Instead of initializing another new Intent to receive the data, just do this:
String id = getIntent().getStringExtra("id");
Put data by intent:
Intent intent = new Intent(mContext, HomeWorkReportActivity.class);
intent.putExtra("subjectName", "Maths");
intent.putExtra("instituteId", 22);
mContext.startActivity(intent);
Get data by intent:
String subName = getIntent().getStringExtra("subjectName");
int insId = getIntent().getIntExtra("instituteId", 0);
If we use an integer value for the intent, we must set the second parameter to 0 in getIntent().getIntExtra("instituteId", 0). Otherwise, we do not use 0, and Android gives me an error.
If used in a FragmentActivity, try this:
The first page extends FragmentActivity
Intent Tabdetail = new Intent(getApplicationContext(), ReceivePage.class);
Tabdetail.putExtra("Marker", marker.getTitle().toString());
startActivity(Tabdetail);
In the fragment, you just need to call getActivity() first,
The second page extends Fragment:
String receive = getActivity().getIntent().getExtras().getString("name");
If you are trying to get extra data in fragments then you can try using:
Place data using:
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER);
Get data using:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
getArguments().getInt(ARG_SECTION_NUMBER);
getArguments().getString(ARG_SECTION_STRING);
getArguments().getBoolean(ARG_SECTION_BOOL);
getArguments().getChar(ARG_SECTION_CHAR);
getArguments().getByte(ARG_SECTION_DATA);
}
Kotlin
First Activity
val intent = Intent(this, SecondActivity::class.java)
intent.putExtra("key", "value")
startActivity(intent)
Second Activity
val value = getIntent().getStringExtra("key")
Suggestion
Always put keys in constant file for more managed way.
companion object {
val PUT_EXTRA_USER = "PUT_EXTRA_USER"
}
You can get any type of extra data from intent, no matter if it's an object or string or any type of data.
Bundle extra = getIntent().getExtras();
if (extra != null){
String str1 = (String) extra.get("obj"); // get a object
String str2 = extra.getString("string"); //get a string
}
and the Shortest solution is:
Boolean isGranted = getIntent().getBooleanExtra("tag", false);
Just a suggestion:
Instead of using "id" or "name" in your i.putExtra("id".....), I would suggest, when it makes sense, using the current standard fields that can be used with putExtra(), i.e. Intent.EXTRA_something.
A full list can be found at Intent (Android Developers).
We can do it by simple means:
In FirstActivity:
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("uid", uid.toString());
intent.putExtra("pwd", pwd.toString());
startActivity(intent);
In SecondActivity:
try {
Intent intent = getIntent();
String uid = intent.getStringExtra("uid");
String pwd = intent.getStringExtra("pwd");
} catch (Exception e) {
e.printStackTrace();
Log.e("getStringExtra_EX", e + "");
}
Pass the intent with value on First Activity:
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("uid", uid.toString());
intent.putExtra("pwd", pwd.toString());
startActivity(intent);
Receive intent on second Activity;-
Intent intent = getIntent();
String user = intent.getStringExtra("uid");
String pass = intent.getStringExtra("pwd");
We use generally two method in intent to send the value and to get the value.
For sending the value we will use intent.putExtra("key", Value); and during receive intent on another activity we will use intent.getStringExtra("key"); to get the intent data as String or use some other available method to get other types of data (Integer, Boolean, etc.).
The key may be any keyword to identify the value means that what value you are sharing.
Hope it will work for you.
You can also do like this
// put value in intent
Intent in = new Intent(MainActivity.this, Booked.class);
in.putExtra("filter", "Booked");
startActivity(in);
// get value from intent
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String filter = bundle.getString("filter");
Getting Different Types of Extra from Intent
To access data from Intent you should know two things.
KEY
DataType of your data.
There are different methods in Intent class to extract different kind of data types.
It looks like this
getIntent().XXXX(KEY) or intent.XXX(KEY);
So if you know the datatype of your varibale which you set in otherActivity you can use the respective method.
Example to retrieve String in your Activity from Intent
String profileName = getIntent().getStringExtra("SomeKey");
List of different variants of methods for different dataType
You can see the list of available methods in Official Documentation of Intent.
This is for adapter , for activity you just need to change mContext
to your Activty name and for fragment you need to change mContext to
getActivity()
public static ArrayList<String> tags_array ;// static array list if you want to pass array data
public void sendDataBundle(){
tags_array = new ArrayList();
tags_array.add("hashtag");//few array data
tags_array.add("selling");
tags_array.add("cityname");
tags_array.add("more");
tags_array.add("mobile");
tags_array.add("android");
tags_array.add("dress");
Intent su = new Intent(mContext, ViewItemActivity.class);
Bundle bun1 = new Bundle();
bun1.putString("product_title","My Product Titile");
bun1.putString("product_description", "My Product Discription");
bun1.putString("category", "Product Category");
bun1.putStringArrayList("hashtag", tags_array);//to pass array list
su.putExtras(bun1);
mContext.startActivity(su);
}
I am using getExtra which is causing the application to crash.
In my activity with button click I am using this code
String test1ID = "test1ID";
Intent intenttesting1 = new Intent(getActivity(), MyActivity.class);
intenttesting1 .putExtra("Test1", test1ID);
startActivity(intenttesting1 );
and then in MyActivity I am using the following code to get the intent
Bundle extras = getIntent().getExtras();
if(extras != null){
if(extras.getString("Test1").equals("test1ID")){ // if an extra has been set
Toast.makeText(getApplicationContext(), "Test 1 Worked", Toast.LENGTH_LONG).show();
}
}
This works perfectly.
I have another button which I want to use to similar with but to send a different string.
However doing so causes the application to crash.
String test2ID = "test2ID";
Intent intenttesting2 = new Intent(getActivity(), MyActivity.class);
intenttesting2 .putExtra("Test2", test2ID);
startActivity(intenttesting2 );
Bundle 2extras= getIntent().getExtras();
if(2extras!= null){
if(2extras.getString("Test2").equals("test2ID")){ // if an extra has been set
Toast.makeText(getApplicationContext(), "Test 1 Worked", Toast.LENGTH_LONG).show();
}
}
Are we not able to send 2 different intent extras to the same activity?
Not sure what I am doing wrong, as both sets of code work, but only 1 set works at one time or the app crashes.
Thanks in advance.
Use yoda notation to protect against null pointer dereference when using .equals
Bundle 2extras= getIntent().getExtras();
if(2extras!= null) {
if("test2ID".equals(2extras.getString("Test2"))){
Toast.makeText(getApplicationContext(), "Test 1 Worked", Toast.LENGTH_LONG).show();
}
}
I think you should be used this for this situation
String test1ID = "test1ID";
Intent intenttesting1 = new Intent(getActivity(), MyActivity.class);
intenttesting1 .putExtra("Test1", test1ID);
startActivity(intenttesting1 );
for next activity
if("test2ID".equals(getIntent().getStringExtra("Test1"))){
Toast.makeText(getApplicationContext(), "Test 1 Worked", Toast.LENGTH_LONG).show();
}
I'm trying to create a shortcut for an another application's activity (which is mine too). The shortcut starts the activity correctly, but just one of the two extras is received (or sent, I don't know). See the code below:
//Setting up the intent
Intent intent = new Intent();
intent.putExtra("num", 12);
intent.putExtra("name", "something");
intent.setComponent(new ComponentName
("com.myanother.app","com.myanother.app.MyActivity"));
And the other activity:
Bundle extras = getIntent().getExtras();
if (extras != null) {
int num = extras.getInt("num"); //this worked
String name = extras.getString("name"); //this gets null
So, what's wrong? And sorry for my English if I made some mistakes.
Try this:
Bundle bund = new Bundle();
bund.putInt("num",12);
bund.putString("name","hello world");
Intent intent = new Intent();
intent.putExtras(bund);
intent.setComponent(new ComponentName
("com.myanother.app","com.myanother.app.MyActivity"));
Instead of trying to put in multiple extras you can try to pass a bundle as an extra. Look at the first answer of this question. The question is similar and the solution should be work.
I have a string in activity2
String message = String.format(
"Current Location \n Longitude: %1$s \n Latitude: %2$s", lat, lng);
I want to insert this string into text field in activity1. How can I do that?
You can use intents, which are messages sent between activities. In a intent you can put all sort of data, String, int, etc.
In your case, in activity2, before going to activity1, you will store a String message this way :
Intent intent = new Intent(activity2.this, activity1.class);
intent.putExtra("message", message);
startActivity(intent);
In activity1, in onCreate(), you can get the String message by retrieving a Bundle (which contains all the messages sent by the calling activity) and call getString() on it :
Bundle bundle = getIntent().getExtras();
String message = bundle.getString("message");
Then you can set the text in the TextView:
TextView txtView = (TextView) findViewById(R.id.your_resource_textview);
txtView.setText(message);
You can send data from one actvity to another with an Intent
Intent sendStuff = new Intent(this, TargetActivity.class);
sendStuff.putExtra(key, stringvalue);
startActivity(sendStuff);
You then can retrieve this information in the second activity by getting the intent and extracting the string extra. Do this in your onCreate() method.
Intent startingIntent = getIntent();
String whatYouSent = startingIntent.getStringExtra(key, value);
Then all you have to do is call setText on your TextView and use that string.
TWO CASES
There are two situations possible when we talk about passing data between activities.
Let's say there are two activities A and B and there is a String X. and you are in Activity A.
Now let's see the two cases
A-------->B
A<--------B
CASE 1:
String X is in A and you want to get it in Activity B.
It is very straightforward.
In Activity A.
1) Create Intent
2) Put Extra value
3) startActivity
Intent i = new Intent(A.this, B.class);
i.putExtra("Your_KEY",X);
startActivity(i)
In Activity B
Inside onCreate() method retrieve string X using the key which you used while storing X (Your_KEY).
Intent i = getIntent();
String s = i.getStringExtra("Your_KEY");
Case 2:
This case is little tricky if u are new to Android
development Because you are in Activity A, you move to Activity B,
collect the string, move back to Activity A and retrieve the
collected String or data. Let's see how to deal with this situation.
In Activity A
1) Create Intent
2) start an activity with a request code.
Intent i = new Intent(A.this, B.class);
startActivityForResult(i,your_req_code);
In Activity B
1) Put string X in intent
2) Set result
3) Finish activity
Intent returnIntent = new Intent();
returnIntent .putString("KEY",X);
setResult(resCode,returnIntent); // for the first argument, you could set Activity.RESULT_OK or your custom rescode too
finish();
Again in Activity A
1) Override onActivityResult method
onActivityResult(int req_code, int res_code, Intent data)
{
if(req_code==your_req_code)
{
String X = data.getStringExtra("KEY")
}
}
Further understanding of Case 2
You might wonder what is the reqCode, resCode in the onActivityResult(int reqCode, resCode, Intent data)
reqCode is useful when you have to identify from which activity you are getting the result from.
Let's say you have two buttons, one button starts Camera (you click a photo and get the bitmap of that image in your Activity as a result), another button starts GoogleMap( you get back the current coordinates of your location as a result). So to distinguish between the results of both activities you start CameraActivty and MapActivity with different request codes.
resCode: is useful when you have to distinguish between how results are coming back to requesting activity.
For eg: You start Camera Activity. When the camera activity starts, you could either take a photo or just move back to requesting activity without taking a photo with the back button press. So in these two situations, your camera activity sends result with different resCode ACTIVITY.RESULT_OK and ACTIVITY.RESULT_CANCEL respectively.
Relevant Links
Read more on Getting result
Say there is EditText et1 in ur MainActivity and u wanna pass this to SecondActivity
String s=et1.getText().toString();
Bundle basket= new Bundle();
basket.putString("abc", s);
Intent a=new Intent(MainActivity.this,SecondActivity.class);
a.putExtras(basket);
startActivity(a);
now in Second Activity, say u wanna put the string passed from EditText et1 to TextView txt1 of SecondActivity
Bundle gt=getIntent().getExtras();
str=gt.getString("abc");
txt1.setText(str);
Intent intent = new Intent(activity1.this, activity2.class);
intent.putExtra("message", message);
startActivity(intent);
In activity2, in onCreate(), you can get the String message by retrieving a Bundle (which contains all the messages sent by the calling activity) and call getString() on it :
Bundle bundle = getIntent().getExtras();
String message = bundle.getString("message");
Intents are intense.
Intents are useful for passing data around the android framework. You can communicate with your own Activities and even other processes. Check the developer guide and if you have specific questions (it's a lot to digest up front) come back.
You can use the GNLauncher, which is part of a utility library I wrote in cases where a lot of interaction with the Activity is required. With the library, it is almost as simple as calling a function on the Activity object with the required parameters. https://github.com/noxiouswinter/gnlib_android/wiki#gnlauncher
In order to insert the text from activity2 to activity1, you first need to create a visit function in activity2.
public void visitactivity1()
{
Intent i = new Intent(this, activity1.class);
i.putExtra("key", message);
startActivity(i);
}
After creating this function, you need to call it from your onCreate() function of activity2:
visitactivity1();
Next, go on to the activity1 Java file. In its onCreate() function, create a Bundle object, fetch the earlier message via its key through this object, and store it in a String.
Bundle b = getIntent().getExtras();
String message = b.getString("key", ""); // the blank String in the second parameter is the default value of this variable. In case the value from previous activity fails to be obtained, the app won't crash: instead, it'll go with the default value of an empty string
Now put this element in a TextView or EditText, or whichever layout element you prefer using the setText() function.
For those people who use Kotlin do this instead:
Create a method with a parameter containing String Object.
Navigate to another Activity
For Example,
// * The Method I Mentioned Above
private fun parseTheValue(#NonNull valueYouWantToParse: String)
{
val intent = Intent(this, AnotherActivity::class.java)
intent.putExtra("value", valueYouWantToParse)
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent)
this.finish()
}
Then just call parseTheValue("the String that you want to parse")
e.g,
val theValue: String
parseTheValue(theValue)
then in the other activity,
val value: Bundle = intent.extras!!
// * enter the `name` from the `#param`
val str: String = value.getString("value").toString()
// * For testing
println(str)
Hope This Help, Happy Coding!
~ Kotlin Code Added By John Melody~
So I was doing this but my output is weird ,
this is the 1st activity
up = findViewById(R.id.button);
up.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, updatestudents.class);
intent.putExtra("updating",updating);
startActivity(intent);
}
});
this is the 2nd activity
Bundle extras = getIntent().getExtras();
if (extras != null) {
Current_Value = getIntent().getStringExtra("updating");
}
u = findViewById(R.id.text);
u.setText("updating " + Current_Value);
Here I am retrieving String in 2nd Activity
And this is my output
enter image description here
How can I send data from one activity (intent) to another?
I use this code to send data:
Intent i=new Intent(context,SendMessage.class);
i.putExtra("id", user.getUserAccountId()+"");
i.putExtra("name", user.getUserFullName());
context.startActivity(i);
First, get the intent which has started your activity using the getIntent() method:
Intent intent = getIntent();
If your extra data is represented as strings, then you can use intent.getStringExtra(String name) method. In your case:
String id = intent.getStringExtra("id");
String name = intent.getStringExtra("name");
In the receiving activity
Bundle extras = getIntent().getExtras();
String userName;
if (extras != null) {
userName = extras.getString("name");
// and get whatever type user account id is
}
// How to send value using intent from one class to another class
// class A(which will send data)
Intent theIntent = new Intent(this, B.class);
theIntent.putExtra("name", john);
startActivity(theIntent);
// How to get these values in another class
// Class B
Intent i= getIntent();
i.getStringExtra("name");
// if you log here i than you will get the value of i i.e. john
Add-up
Set Data
String value = "Hello World!";
Intent intent = new Intent(getApplicationContext(), NewActivity.class);
intent.putExtra("sample_name", value);
startActivity(intent);
Get Data
String value;
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
value = bundle.getString("sample_name");
}
Instead of initializing another new Intent to receive the data, just do this:
String id = getIntent().getStringExtra("id");
Put data by intent:
Intent intent = new Intent(mContext, HomeWorkReportActivity.class);
intent.putExtra("subjectName", "Maths");
intent.putExtra("instituteId", 22);
mContext.startActivity(intent);
Get data by intent:
String subName = getIntent().getStringExtra("subjectName");
int insId = getIntent().getIntExtra("instituteId", 0);
If we use an integer value for the intent, we must set the second parameter to 0 in getIntent().getIntExtra("instituteId", 0). Otherwise, we do not use 0, and Android gives me an error.
If used in a FragmentActivity, try this:
The first page extends FragmentActivity
Intent Tabdetail = new Intent(getApplicationContext(), ReceivePage.class);
Tabdetail.putExtra("Marker", marker.getTitle().toString());
startActivity(Tabdetail);
In the fragment, you just need to call getActivity() first,
The second page extends Fragment:
String receive = getActivity().getIntent().getExtras().getString("name");
If you are trying to get extra data in fragments then you can try using:
Place data using:
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER);
Get data using:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
getArguments().getInt(ARG_SECTION_NUMBER);
getArguments().getString(ARG_SECTION_STRING);
getArguments().getBoolean(ARG_SECTION_BOOL);
getArguments().getChar(ARG_SECTION_CHAR);
getArguments().getByte(ARG_SECTION_DATA);
}
Kotlin
First Activity
val intent = Intent(this, SecondActivity::class.java)
intent.putExtra("key", "value")
startActivity(intent)
Second Activity
val value = getIntent().getStringExtra("key")
Suggestion
Always put keys in constant file for more managed way.
companion object {
val PUT_EXTRA_USER = "PUT_EXTRA_USER"
}
You can get any type of extra data from intent, no matter if it's an object or string or any type of data.
Bundle extra = getIntent().getExtras();
if (extra != null){
String str1 = (String) extra.get("obj"); // get a object
String str2 = extra.getString("string"); //get a string
}
and the Shortest solution is:
Boolean isGranted = getIntent().getBooleanExtra("tag", false);
Just a suggestion:
Instead of using "id" or "name" in your i.putExtra("id".....), I would suggest, when it makes sense, using the current standard fields that can be used with putExtra(), i.e. Intent.EXTRA_something.
A full list can be found at Intent (Android Developers).
We can do it by simple means:
In FirstActivity:
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("uid", uid.toString());
intent.putExtra("pwd", pwd.toString());
startActivity(intent);
In SecondActivity:
try {
Intent intent = getIntent();
String uid = intent.getStringExtra("uid");
String pwd = intent.getStringExtra("pwd");
} catch (Exception e) {
e.printStackTrace();
Log.e("getStringExtra_EX", e + "");
}
Pass the intent with value on First Activity:
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("uid", uid.toString());
intent.putExtra("pwd", pwd.toString());
startActivity(intent);
Receive intent on second Activity;-
Intent intent = getIntent();
String user = intent.getStringExtra("uid");
String pass = intent.getStringExtra("pwd");
We use generally two method in intent to send the value and to get the value.
For sending the value we will use intent.putExtra("key", Value); and during receive intent on another activity we will use intent.getStringExtra("key"); to get the intent data as String or use some other available method to get other types of data (Integer, Boolean, etc.).
The key may be any keyword to identify the value means that what value you are sharing.
Hope it will work for you.
You can also do like this
// put value in intent
Intent in = new Intent(MainActivity.this, Booked.class);
in.putExtra("filter", "Booked");
startActivity(in);
// get value from intent
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String filter = bundle.getString("filter");
Getting Different Types of Extra from Intent
To access data from Intent you should know two things.
KEY
DataType of your data.
There are different methods in Intent class to extract different kind of data types.
It looks like this
getIntent().XXXX(KEY) or intent.XXX(KEY);
So if you know the datatype of your varibale which you set in otherActivity you can use the respective method.
Example to retrieve String in your Activity from Intent
String profileName = getIntent().getStringExtra("SomeKey");
List of different variants of methods for different dataType
You can see the list of available methods in Official Documentation of Intent.
This is for adapter , for activity you just need to change mContext
to your Activty name and for fragment you need to change mContext to
getActivity()
public static ArrayList<String> tags_array ;// static array list if you want to pass array data
public void sendDataBundle(){
tags_array = new ArrayList();
tags_array.add("hashtag");//few array data
tags_array.add("selling");
tags_array.add("cityname");
tags_array.add("more");
tags_array.add("mobile");
tags_array.add("android");
tags_array.add("dress");
Intent su = new Intent(mContext, ViewItemActivity.class);
Bundle bun1 = new Bundle();
bun1.putString("product_title","My Product Titile");
bun1.putString("product_description", "My Product Discription");
bun1.putString("category", "Product Category");
bun1.putStringArrayList("hashtag", tags_array);//to pass array list
su.putExtras(bun1);
mContext.startActivity(su);
}