This question already has answers here:
How to pass a value from one Activity to another in Android? [duplicate]
(7 answers)
Closed 9 years ago.
In Activity1, I input some data like name and address. When I click the next button, there will be another input form. What I want to do is, when I click BACK, I will return to Activity1 and the data I entered there previously is shown.
HELP please :)
=============
UPDATED: Activity1
private void startActivityForResult()
{
TextView textname = (TextView) findViewById(R.id.username);
TextView textaddress = (TextView) findViewById(R.id.useraddress);
Intent intent = new Intent(this, GetInformation.class);
//intent.putExtras(getIntent());
intent.putExtra("username", textname.getText().toString());
intent.putExtra("useradd", textaddress.getText().toString());
startActivityForResult(intent, 0);
}
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
TextView textname = (TextView) findViewById(R.id.username);
TextView textaddress = (TextView) findViewById(R.id.useraddress);
textname.setText(data.getStringExtra("returnname").toString());
textaddress.setText(data.getStringExtra("returnadd").toString());
}
Activity2
private void startActivityForResult()
{
final String username;
final String useraddress;
Intent intent = getIntent();
//intent.putExtras(getIntent());
username = getIntent().getStringExtra("username");
useraddress = getIntent().getStringExtra("useradd");
intent.putExtra("returnname", username);
intent.putExtra("returnadd", useraddress);
setResult(0, intent);
}
There's a simple way to do this in Android : startActivityForResult. Basically, when you launch the activity, you say that you are expecting a result. The other activity can then add information that will be returned to the starting activity. Here's a very simple code sample from the official doc :
public class MyActivity extends Activity {
...
static final int PICK_CONTACT_REQUEST = 0;
protected boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
// When the user center presses, let them pick a contact.
startActivityForResult(
new Intent(Intent.ACTION_PICK,
new Uri("content://contacts")),
PICK_CONTACT_REQUEST);
return true;
}
return false;
}
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (requestCode == PICK_CONTACT_REQUEST) {
if (resultCode == RESULT_OK) {
// A contact was picked. Here we will just display it
// to the user.
startActivity(new Intent(Intent.ACTION_VIEW, data));
}
}
}
}
You can get a much more complete description of all this on the Activity page in the official doc (section Starting Activities and Getting Results).
Save Activity1 state in method onSaveInstanceState, and then in method
void onCreate(Bundle savedInstanceState)
you can restore state, using savedInstanceState.
Or, if you want pass entered data to second activity, you can place data in intent.
Sample:
Intent i = new Intent(FirstActivity.this, SecondActivity.class);
i.putExtra("Key", "Value");
startActivityForResult(i, 0);
in Second Activity you can get data:
getIntent().getStringExtra("Key");
To return result from second activity:
Intent data = new Intent();
data.put("key", "value");
setResult(RESULT_OK, data);
then you can retrieve data in first activity using
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
data.getStringExtra("key");
}
Related
I searched a lot and tried things but the onActivityResult function isn't launched when the intent from which I try to get a string information is closed.
I use Visual Studio to write this application, this is my code :
The click event that opens the activity where users can type strings :
private void Btn_Valid_Click(object sender, EventArgs e)
{
----
Intent intent = new Intent(this, typeof(activity_OF_TransfertChxChmb));
StartActivityForResult(intent, 0);
----
}
The function in the openned Intent that should return the string information :
private void Validate()
{
string stringToPassBack = tb_Store.Text;
// put the String to pass back into an Intent and close this activity
Intent intent = new Intent();
intent.PutExtra("result", stringToPassBack);
SetResult(Result.Ok, intent);
Finish();
}
And the onActivityResult function that should be launched in the first activity:
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
base.onActivityResult(requestCode, 0, data);
if (requestCode == 0)
{
if (resultCode == -1) // Ok
{
string result = data.GetStringExtra("result");
}
if (resultCode == 0) // Canceled
{
//Write your code if there's no result
}
}
}
I am missing something, but can't figure out what.
Thank you for your help.
You are adding the extra via:
intent.PutExtra(Intent.ExtraText, stringToPassBack);
Your key is Intent.ExtraText.
You are retrieving the extra via:
string result = data.GetStringExtra("result");
Your key is "result".
So, perhaps Intent.ExtraText does not equal "result". You need to use the same key in both places.
I am trying to get results back from intents in android studio.
In my main I start an activity and use startActivityForResult(intent, 1)
I then use get results in mainActivity from activity 2's setResults()
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == RESULT_OK){
Bundle extras = data.getExtras();
if (extras != null) {
String name = extras.getString("FIRSTNAME");
String Lname = extras.getString("LASTNAME");
int ID = extras.getInt("ID");
//TODO: Get the list fragment to newinstance with out new arraylist
Person p = new Person(name, Lname, ID);
people.add(p);
getFragmentManager().beginTransaction().replace(R.id.content_main, FullList.newInstance(people)).commit();
}
In my fragment in activity 1 I am calling a new startActivityForResult(i, 2)
How do i get my main activity to grab the setResults()
from Activity 3?
Activity 3 is doing this:
Intent deleteIntent = new Intent();
deleteIntent.putExtra("FNAME", first);
deleteIntent.putExtra("LNAME", last);
deleteIntent.putExtra("ID", num);
setResult(RESULT_OK, deleteIntent);
finish();
I am trying to have my main activity call if (requestCode == 2)
But it works to no avail.
Here is the all the onActivityResult for reference:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == RESULT_OK){
Bundle extras = data.getExtras();
if (extras != null) {
String name = extras.getString("FIRSTNAME");
String Lname = extras.getString("LASTNAME");
int ID = extras.getInt("ID");
//TODO: Get the list fragment to newinstance with out new arraylist
Person p = new Person(name, Lname, ID);
people.add(p);
getFragmentManager().beginTransaction().replace(R.id.content_main, FullList.newInstance(people)).commit();
}
// NOW SEEING IF THE DETAILS SCREEN PASSED BACK RESULTS
} else if (requestCode == 2) {
if (resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
if (extras != null) {
String name = extras.getString("FNAME");
String Lname = extras.getString("LNAME");
int ID = extras.getInt("ID");
Person p = new Person(name, Lname, ID);
// Delete happens here //
if (people.contains(p)) {
people.remove(p);
// If empty show blank frag, if not, update list //
if (people.isEmpty()) {
getFragmentManager().beginTransaction().replace(R.id.content_main, BlankList.newInstance());
} else {
getFragmentManager().beginTransaction().replace(R.id.content_main, FullList.newInstance(people)).commit();
}
} else {
Toast.makeText(this, "DIDNT RECEIVE SAME INFO", Toast.LENGTH_SHORT).show();
}
}
}
}
// END ELSE CHECK
}
}
Here is the code that is calling the startActivityForResult() in the Fragment on activity 1.
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
//super.onListItemClick(l, v, position, id);
ArrayList<Person> people = (ArrayList<Person>) getArguments().getSerializable(ARG_People);
if (people != null && position != -1) {
Person listPerson = people.get(position);
Intent i = new Intent("OPENDETAILS");
i.putExtra("NAME", listPerson.name);
i.putExtra("LASTNAME", listPerson.lName);
i.putExtra("ID", listPerson.ID);
startActivityForResult(i, 2);
} else {
Toast.makeText(getActivity(), "EMPTY LIST ERROR", Toast.LENGTH_SHORT).show();
}
}
It's a little unclear what you're trying to do, but it sounds like:
Activity1 starts Activity2 for result
Activity2 starts Activity3 for result
Activity3 returns a result
Activity1 is expected receive Activity3's result.
If I got that right then the key element that seems to be missing here is that you are expecting Activity1 to get a result from Activity3 even though it was Activity2 that started it for result. In this case you should implement onActivityResult in Activity2, handle the results coming back from Activity3 and set them as Activity2's results to pass back to Activity1 and then finish; An activity will only receive results from activities it directly starts via startActivityForResult.
Use different code to launch different activities,
such as
startActivtityForResult(new Intent(this,Person1.class),1);
startActivtityForResult(new Intent(this,Person2.class),2);
startActivtityForResult(new Intent(this,Person3.class),3);
then on activityresult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (resultCode) {
case 1:
//implement your code here
break;
case 2:
//implement your code here
break;
case 3:
//implement your code here
break;
}
}
then set Retrun result in these classes
Person1.class
return_intent.putExtra("result", 1);
setResult(1, return_intent);
Person2.class
Person1.class
return_intent.putExtra("result", 2);
setResult(2, return_intent);
Person3.class
Person1.class
return_intent.putExtra("result", 3);
setResult(3, return_intent);
This question already has answers here:
Using intents to pass data between activities
(7 answers)
Closed 6 years ago.
Hi I am getting the problem to send the data from second activity to first activity
Intent i=new Intent();
i.setClass(SecondActivity.this,MainActivity.class);
Toast.makeText(SecondActivity.this, "this is second activity", Toast.LENGTH_SHORT).show();
String name=ed1.getText().toString();
i.putExtra("ok",name);
setResult(RESULT_OK, i);
startActivity(i);
how can we recive the data on first activity
first, define a variable in you first activity like this (100 is just random, pick whatever you want):
private static final int SECOND_ACTIVITY = 100;
then in your first activity you start the second activity like this:
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
startActivityForResult(intent, SECOND_ACTIVITY);
also override onActivityResult in your first activity:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SECOND_ACTIVITY) {
if (resultCode == RESULT_OK) {
String foo = data.getStringExtra("foo");
}
}
}
when you finish your second activity put you data, like this:
Intent data = new Intent();
data.putExtra("foo", "bar");
setResult(RESULT_OK, data);
finish();
Here is working example for getting data from second activity.
//First activity
private static final int PLAY_GAME = 1010;
#Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
if (requestCode == PLAY_GAME && resultCode == RESULT_OK) {
String getData = data.getExtras().getString("returnStr");
}
super.onActivityResult(requestCode, resultCode, data);
}
//second activity
Intent i = getIntent();
i.putExtra("returnStr", data);
setResult(RESULT_OK,i);
finish();
This question already has answers here:
How do I pass data between Activities in Android application?
(53 answers)
Closed 8 years ago.
My app has 2 activites.
The first activity is just a simple form where a user enters course information(class title, professor..etc.) the first activity passes the data which is supposed to be stored in a list.
In the second activity. The problem is that only the first course gets stored in the list, after the first time nothing new gets added to the second activity.
How can i do this ?
In your first activity :
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("login", jObj.getString(KEY_LOGIN));
intent.putExtra("mdp", jObj.getString(KEY_MDP));
intent.putExtra("prenom", jObj.getString(KEY_PRENOM));
intent.putExtra("nom", jObj.getString(KEY_NOM));
intent.putExtra("mail", jObj.getString(KEY_MAIL));
intent.putExtra("tel", jObj.getString(KEY_TEL));
startActivity(intent);
In your second activity :
Intent intent = getIntent();
if (intent != null) {
login = intent.getStringExtra("login");
mdp = intent.getStringExtra("mdp");
items.add(intent.getStringExtra("login"));
items.add(intent.getStringExtra("prenom"));
items.add(intent.getStringExtra("nom"));
items.add(intent.getStringExtra("mail"));
items.add(intent.getStringExtra("tel"));
}
Generally you can pass data from one Activity to another with an Intent like this:
In your first Activity:
// Create your Intent
Intent intent = new Intent(context, TargetActivity.class);
// Now you can add extras to the intent, you identify extras with a String key
intent.putExtra("text", someString);
intent.putExtra("amount", someInteger);
// Then you start your Activity with this Intent
startActivity(intent);
In your second Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Only get data from Intent when the Activity is new
if(savedInstanceState == null) {
Intent intent = getIntent();
// Now you read the values from the Intent
String someString = intent.getStringExtra("text");
int someInteger = intent.getIntExtra("amount", 0);
}
}
hey its simple look at the code
for sending
Intent i = new Intent(getApplicationContext(), Confirmation.class)
i.putExtra("name",etName.getText().toString()));
i.putExtra("pass",etPass.getText().toString());
startActivity(i);
for recieving in next activity
Bundle extras = getIntent().getExtras();
String strEmployeeID="";
if (extras != null)
{
String value = extras.getString("name");
String value1 = extras.getString("pass");
//
Toast.makeText(getBaseContext(), value, Toast.LENGTH_LONG).show();
strEmployeeID = value;
strEmployeePass = value1;
}
just simply do it like that:
passing data from 1st activity to 2nd activity:
Intent intent = new Intent(yourafirstctivity.this,Yoursecondactivity.class);
intent.putExtra("yourkey", yourvalue);
intent.putExtra("yourkey", yourvalue);
intent.putExtra("yourkey", yourvalue);
startActivity(intent);
and get the data from 1st activity to 2nd activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.yourlayout);
String yourstring = getIntent().getExtras().getString("yourkey");
String yourstring = getIntent().getExtras().getString("yourkey");
String yourstring = getIntent().getExtras().getString("yourkey");
}
if you want to send data between two Activities .You must call following one,
startActivityForResult(getcontext(), SecondActivity.class);
On calling this,Activity starts the second.In turn, second response to this intent and reply back with necessary data.
public void startActivityForResult(Intent intent, int requestCode, Bundle options) {
if (mParent == null) {
Instrumentation.ActivityResult ar =
mInstrumentation.execStartActivity(
this, mMainThread.getApplicationThread(), mToken, this,
intent, requestCode, options);
if (ar != null) {
mMainThread.sendActivityResult(
mToken, mEmbeddedID, requestCode, ar.getResultCode(),
ar.getResultData());
}
if (requestCode >= 0) {
mStartedActivity = true;
}
} else {
if (options != null) {
mParent.startActivityFromChild(this, intent, requestCode, options);
} else {
// Note we want to go through this method for compatibility with
// existing applications that may have overridden it.
mParent.startActivityFromChild(this, intent, requestCode);
}
}
}
Following one you must call this on the First Activity (from where the intent called).It helps to recieves the reply data from second Activity.
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(!isFeatureInstalled(getContext()))
return;
if(requestCode == GET_REMINDER_DETAILS && resultCode == Activity.RESULT_OK)
{
mFilled = true;
fillDataFromIntent(data);
checkALertRequired.setChecked(true);
}
}
Here is my first activity code from where I call the second Activity:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT){
startActivityForResult(new Intent("chap.two.Chapter2Activity2"),request_Code);
}
return false;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == request_Code) {
if (resultCode == RESULT_OK)
Toast.makeText(this,data.getData().toString(),Toast.LENGTH_SHORT).show();
}
}
And here is a code of chap.two.Chapter2Activity2:
Button n = (Button) findViewById(R.id.btn_OK);
n.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent data = new Intent();
//---get the EditText view---
EditText txt_username =(EditText) findViewById(R.id.txt_username);
//---set the data to pass back---
data.setData(Uri.parse(txt_username.getText().toString()));
setResult(RESULT_OK, data);
//---closes the activity---
finish();
}
});
here I see that setResult(RESULT_OK, data) has two arguments but
onActivityResult(int requestCode, int resultCode, Intent data) has three and I want know how onActivityResult gets value for third parameter? How it works can anyone tell me? Why isn't this error ?
When you call Activity.startActivityForResult(), you set the requestCode. Later, this request code is needed by onActivityResult() in order to determine what Activity is sending data to it. We don't need to supply requestCode again on setResult() because the requestCode is carried along.
The data is intent data returned from launched intent. We usually use this data when we set extras on the called intent.
Consider this example:
CALL SECOND ACTIVITY
Intent i = new Intent(MainActivity.this, CheckActivity.class);
startActivityForResult(i, REQUEST_CODE_CHECK);
ON SECOND ACTIVITY, SET INTENT RESULT
getIntent().putExtra("TADA", "bla bla bla");
setResult(RESULT_OK, getIntent());
finish();
BACK TO FIRST ACTIVITY, ONACTIVITYRESULT()
if(requestCode == REQUEST_CODE_CHECK && resultCode == RESULT_OK){
text1.setText(data.getExtras().getString("TADA") );
}
There you go. You should now understand what is Intent data and how to set and fetch the value.
Third parameter is Intent, which you sent from the sub-Activity(Second Activity, which is going to finish).
If you want to perform some calculations or fetch some username/password in sub-activity and you want to send the result to the main activity, then you place the data in the intent and will return to the Main activity before finish().
After that you will check in onActivityResult(int, int, Intent) in main activity for the result with Intent parameter.
Example::
MainActivity:
public void onClick(View view) {
Intent i = new Intent(this, subActivity.class);
startActivityForResult(i, REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
if (data.hasExtra("username") && data.hasExtra("password")) {
String username = data.getExtras().getString("username");
String password = data.getExtras().getString("password");
}
}
subActivity::
#Override
public void finish() {
// Create one data intent
Intent data = new Intent();
data.putExtra("username", "Bla bla bla..");
data.putExtra("password", "*****");
setResult(RESULT_OK, data);
super.finish();
}