How to pass data from 2nd activity to 1st activity when pressed back? - android
Asked Answered
F

8

212

I've 2 activities, Activity1 and Activity2.

In Activity1 I've a Button and TextView. When the button is clicked Activity2 is started.

In Activity2 I've an EditText.

I want to display the data retrieved from EditText in Activity2 in the TextView in Activity1 when back is pressed from Activity2.

can someone help me with the code to make this work?

Folie answered 12/1, 2013 at 10:24 Comment(8)
read about startActivityForResultInductee
#2695447Spindry
Another way: Activity2 puts the value in persistent storage and Activity1 reads it from there.Typewriter
@kumareloaded: Could you please share the solution here. Pastebin isn't working in my country as of now.Marquismarquisate
Possible duplicate of How to pass the values from one activity to previous activitySwiger
if I am coming from activity 3 the what will be code...Isolde
Possible duplicate of How do I pass data between Activities in Android application?Tyrothricin
onActivityResult is deprecated use this method #62671606Noonday
G
377

Start Activity2 with startActivityForResult and use setResult method for sending data back from Activity2 to Activity1. In Activity1 you will need to override onActivityResult for updating TextView with EditText data from Activity2.

For example:

In Activity1, start Activity2 as:

Intent i = new Intent(this, Activity2.class);
startActivityForResult(i, 1);

In Activity2, use setResult for sending data back:

Intent intent = new Intent();
intent.putExtra("editTextValue", "value_here")
setResult(RESULT_OK, intent);        
finish();

And in Activity1, receive data with onActivityResult:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1) {
         if(resultCode == RESULT_OK) {
             String strEditText = data.getStringExtra("editTextValue");
         }     
    }
} 

If you can, also use SharedPreferences for sharing data between Activities.

Grigson answered 12/1, 2013 at 10:32 Comment(10)
thanks man, if you can could you help me with the similar coding part for SharedPreferences to do the same :)Folie
@Folie : most welcome friend. if you want to do same using SharedPreferences then see this exampleBoarish
tired that man had probs doing it but using startActivityForResult it works fine. it will be helpful if you can provide me the code for above scenario using SharedPref :)Folie
@Folie : if you give me code links of both classes with what u have tried using pastebin.com then i will edit your codeBoarish
nope bro :( here's my complete code with SharedPref(not working) and startActivityForResult(enclosed as comment which works fine).. pastebin.com/gydfWpHNFolie
@Folie : now use this code and this will workBoarish
@ρяσѕρєяK: Could you please share the code for above scenario using SharedPref in your answer. Pastebin doesn't open up in many countries. Sharing it here would be of great help, thank you.Marquismarquisate
I cant believe! After all these years, i became aware of startActivityForResult for the first time. Thank you so much!!!Strathspey
que agradable sujetoCarper
by the way, this option was deprecated. so that, you must to use activityResultLauncher to pass dataLambard
M
33

Activity1 should start Activity2 with startActivityForResult().

Activity2 should use setResult() to send data back to Activity1.

In Activity2,

@Override
public void onBackPressed() {
    String data = mEditText.getText();
    Intent intent = new Intent();
    intent.putExtra("MyData", data);
    setResult(resultcode, intent);
}

In Activity1,

onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 1) {
        if(resultCode == RESULT_OK) {
            String myStr=data.getStringExtra("MyData");
            mTextView.setText(myStr);
        }
    }
}
Matheny answered 12/1, 2013 at 10:30 Comment(2)
@Matheny I guess because you didn't mention activity1 should start activity2 with startactivityforresult.Militarist
@Militarist : That could very well be it! Thanks for pointing it out! Edited my answer. :)Matheny
G
23

Other answers were not working when I put setResult in onBackPressed. Commenting call to super onBackPressed and calling finish manually solves the problem:

@Override
public void onBackPressed() {
    //super.onBackPressed();
    Intent i = new Intent();
    i.putExtra(EXTRA_NON_DOWNLOADED_PAGES, notDownloaded);
    setResult(RESULT_OK, i);
    finish();
}

And in first activity:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == QUEUE_MSG) {
        if (resultCode == RESULT_OK) {
            Serializable tmp = data.getSerializableExtra(MainActivity.EXTRA_NON_DOWNLOADED_PAGES);
            if (tmp != null)
                serializable = tmp;
        }
    }
}
Germaine answered 5/11, 2015 at 3:19 Comment(1)
Good point. The onBackPressed() method is overwritten, so the back function doesn't work. You have to manually call finish().Mala
I
7

Take This as an alternate to startActivityforResult.But keep in mind that for such cases this approach can be expensive in terms of performance but in some cases you might need to use.

In Activity2,

@Override
public void onBackPressed() {
String data = mEditText.getText();
SharedPreferences sp = getSharedPreferences("LoginInfos", 0);
Editor editor = sp.edit();
editor.putString("email",data);
editor.commit();
}

In Activity1,

 @Override
public void onResume() {
SharedPreferences sp = getSharedPreferences("LoginInfos", 0);
String  dataFromOtherAct= sp.getString("email", "no email");
} 
Illustrious answered 26/1, 2015 at 15:3 Comment(3)
This cannot be used for object (only string, boolean, etc)Germaine
In my case I was launching an activity from a list item in MainActivity and wanted to get user created data back to that list item. startActivityForResult() was not available to me in this case where I was using mContext.startActivity(). @Illustrious example here was a helpful work around.Tamatamable
for my that is a bad election. exist actionForResultForecourse
D
3

this is your first Activity1.

public class Activity1 extends Activity{
private int mRequestCode = 100;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Intent intent = new Intent(this, Activity2.class);
    startActivityForResult(intent, mRequestCode);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == mRequestCode && resultCode == RESULT_OK){
        String editTextString = data.getStringExtra("editText");
    }
}
}

From here you are starting your Activity2.class by using startActivityForResult(mRequestCode, Activity2.class);

Now this is your second Activity, name is Activity2

public class Activity2 extends Activity {
private EditText mEditText;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //mEditText = (EditText)findViewById(R.id.edit_text);

    Intent intent = new Intent();
    intent.putExtra("editText", mEditText.getText().toString());
    setResult(RESULT_OK, intent);
}

}

Now when you done with your second Activity then you call setResult() method, from onBackPress() or from any button click when your Activity2 will destroy then your Activity1's call back method onActivityResult() will call from there you can get your data from intent..

Hope it will help to you...:)

Donets answered 12/1, 2013 at 10:50 Comment(0)
H
3

2021 After the new update in java:

Use activityresultlauncher() instead of startactivityforresult() in the MainActivity.

ActivityResultLauncher<Intent> activityResultLaunch = registerForActivityResult(
        new ActivityResultContracts.StartActivityForResult(),
        new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if (result.getResultCode() == 123) {
                    Intent data = result.getData();
                    String myStr = data.getStringExtra("MyData");

                    if (!TextUtils.isEmpty(myStr )) {
                        myTextView.setText(myStr);
                    }

                }
            }
        });

Inside onCreate():

myBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, Second.class);
            activityResultLaunch.launch(intent);
        }
    });

Inside the SecondActivity (outside onCreate):

@Override
public void onBackPressed() {
    String data = myEditText.getText().toString();
    Intent intent = new Intent();
    intent.putExtra("MyData", data);
    setResult(123, intent);
    finish();
}
Hampden answered 11/1, 2022 at 6:26 Comment(2)
override fun finish() { setResult(RESULT_OK, Intent().apply { putExtra("Parameters", Gson().toJson(result)) }) super.finish() } We can set the activity result by overriding the finish() function as well. So this method will work even user leave the activity without touching back button...Rafaello
is it possible to use same like this in Fragment also, because I am luanching Intent from Fragment to activity and try to receive data from Activity to Fragment?Ticktock
T
2

and I Have an issue which I wanted to do this sending data type in a Soft Button which I'd made and the softKey which is the default in every Android Device, so I've done this, first I've made an Intent in my "A" Activity:

            Intent intent = new Intent();
            intent.setClass(context, _AddNewEmployee.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            startActivityForResult(intent, 6969);
            setResult(60);

Then in my second Activity, I've declared a Field in my "B" Activity:

private static int resultCode = 40;

then after I made my request successfully or whenever I wanted to tell the "A" Activity that this job is successfully done here change the value of resultCode to the same I've said in "A" Activity which in my case is "60" and then:

private void backToSearchActivityAndRequest() {
    Intent data = new Intent();
    data.putExtra("PhoneNumber", employeePhoneNumber);
    setResult(resultCode, data);
    finish();
}

@Override
public void onBackPressed() {
    backToSearchActivityAndRequest();
}

PS: Remember to remove the Super from the onBackPressed Method if you want this to work properly.

then I should call the onActivityResult Method in my "A" Activity as well:

   @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 6969 && resultCode == 60) {
            if (data != null) {
                    user_mobile = data.getStringExtra("PhoneNumber");
                    numberTextField.setText(user_mobile);
                    getEmployeeByNumber();
            }
        }
    }

that's it, hope it helps you out. #HappyCoding;

Towage answered 16/7, 2018 at 10:35 Comment(0)
G
1

TL;DR Use Activity.startActivityForResult

Long answer:

You should start by reading the Android developer documentation. Specifically the topic of your question is covered in the Starting Activities and Getting Results section of the Activity documentation.

As for example code, the Android SDK provides good examples. Also, other answers here give you short snippets of sample code to use.

However, if you are looking for alternatives, read this SO question. This is a good discussion on how to use startActivityForResults with fragments, as well as couple othe approaches for passing data between activities.

Gerigerianna answered 12/1, 2013 at 10:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.