Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send string from one activity to another?

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?

like image 980
Luch Filip Avatar asked Aug 09 '13 12:08

Luch Filip


People also ask

How do you move from one activity to another?

To create the second activity, follow these steps: In the Project window, right-click the app folder and select New > Activity > Empty Activity. In the Configure Activity window, enter "DisplayMessageActivity" for Activity Name. Leave all other properties set to their defaults and click Finish.


1 Answers

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); 

Hope this helps !

like image 90
jbihan Avatar answered Sep 21 '22 09:09

jbihan