简体   繁体   English

按下后如何将数据从第二个活动传递到第一个活动? - android

[英]How to pass data from 2nd activity to 1st activity when pressed back? - android

I've 2 activities, Activity1 and Activity2 .我有 2 个活动, Activity1Activity2

In Activity1 I've a Button and TextView .Activity1我有一个ButtonTextView When the button is clicked Activity2 is started.单击按钮时, Activity2将启动。

In Activity2 I've an EditText .Activity2我有一个EditText

I want to display the data retrieved from EditText in Activity2 in the TextView in Activity1 when back is pressed from Activity2 .当从Activity2按下返回时,我想在Activity1TextView中的Activity2中显示从EditText检索到的数据。

can someone help me with the code to make this work?有人可以帮我编写代码来完成这项工作吗?

Start Activity2 with startActivityForResult and use setResult method for sending data back from Activity2 to Activity1. 使用startActivityForResult启动Activity2,并使用setResult方法将数据从Activity2发送回Activity1。 In Activity1 you will need to override onActivityResult for updating TextView with EditText data from Activity2. 在Activity1中,您将需要重写onActivityResult ,以使用Activity2中的EditText数据更新TextView

For example: 例如:

In Activity1 , start Activity2 as: Activity1中 ,以以下方式启动Activity2:

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

In Activity2 , use setResult for sending data back: Activity2中 ,使用setResult将数据发送回去:

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

And in Activity1 , receive data with onActivityResult : Activity1中 ,使用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. 如果可以,还可以使用SharedPreferences在Activity之间共享数据。

Activity1 should start Activity2 with startActivityForResult() . Activity1应该使用startActivityForResult()启动Activity2

Activity2 should use setResult() to send data back to Activity1 . Activity2应该使用setResult()将数据发送回Activity1

In Activity2 , Activity2中

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

In Activity1 , 活动1中

onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 1) {
        if(resultCode == RESULT_OK) {
            String myStr=data.getStringExtra("MyData");
            mTextView.setText(myStr);
        }
    }
}

Other answers were not working when I put setResult in onBackPressed . 当我将setResult放在onBackPressed时,其他答案onBackPressed Commenting call to super onBackPressed and calling finish manually solves the problem: 评论对super onBackPressed调用finish手动finish调用可以解决此问题:

@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;
        }
    }
}

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. 将此作为StartActivityforResult的替代方法。但是请记住,在这种情况下,这种方法的性能可能会很昂贵,但在某些情况下可能需要使用。

In Activity2, 在活动2中,

@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, 在活动1中,

 @Override
public void onResume() {
SharedPreferences sp = getSharedPreferences("LoginInfos", 0);
String  dataFromOtherAct= sp.getString("email", "no email");
} 

Read these: 阅读以下内容:

  1. Return result to onActivityResult() 返回结果到onActivityResult()
  2. Fetching Result from a called activity - Android Tutorial for Beginners 从调用的活动中获取结果-适用于初学者的Android教程

These articles will help you understand how to pass data between two activities in Android. 这些文章将帮助您了解如何在Android的两个活动之间传递数据。

this is your first Activity1. 这是您的第一个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); 从这里开始,您将使用startActivityForResult(mRequestCode,Activity2.class)启动Activity2.class。

Now this is your second Activity, name is Activity2 现在这是您的第二个活动,名称是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.. 现在,当您完成第二个Activity时,您可以从onBackPress()或从任何按钮单击中调用setResult()方法,当Activity2销毁时,将从那里调用您的Activity1的回调方法onActivityResult() ,您可以从intent中获取数据..

Hope it will help to you...:) 希望对您有帮助... :)

From your FirstActivity call the SecondActivity using startActivityForResult() method. 在您的FirstActivity中,使用startActivityForResult()方法调用SecondActivity。

For example: 例如:

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

In your SecondActivity set the data which you want to return back to FirstActivity. 在您的SecondActivity中,设置要返回到FirstActivity的数据。 If you don't want to return back, don't set any. 如果您不想返回,请不要进行任何设置。

For example: In secondActivity if you want to send back data: 例如:如果要发送回数据,请在secondActivity中:

Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(Activity.RESULT_OK,returnIntent);
finish();

If you don't want to return data: 如果您不想返回数据:

Intent returnIntent = new Intent();
setResult(Activity.RESULT_CANCELED, returnIntent);
finish();

Now in your FirstActivity class write following code for the onActivityResult() method. 现在,在FirstActivity类中,为onActivityResult()方法编写以下代码。

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 1) {
        if(resultCode == Activity.RESULT_OK){
            String result=data.getStringExtra("result");
        }
        if (resultCode == Activity.RESULT_CANCELED) {
            //Write your code if there's no result
        }
    }
}

TL;DR Use Activity.startActivityForResult TL; DR使用Activity.startActivityForResult

Long answer: 长答案:

You should start by reading the Android developer documentation. 您应该先阅读Android开发人员文档。 Specifically the topic of your question is covered in the Starting Activities and Getting Results section of the Activity documentation. 具体而言, Activity文档的“ Starting Activities and Getting Results部分涵盖了您的问题主题。

As for example code, the Android SDK provides good examples. 作为示例代码,Android SDK提供了很好的示例。 Also, other answers here give you short snippets of sample code to use. 另外,这里的其他答案也为您提供了一些简短的示例代码片段供您使用。

However, if you are looking for alternatives, read this SO question . 但是,如果您正在寻找替代品,请阅读此SO问题 This is a good discussion on how to use startActivityForResults with fragments, as well as couple othe approaches for passing data between activities. 这是关于如何将startActivityForResults与片段以及如何在活动之间传递数据的其他方法结合使用的很好的讨论。

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 : 和我有我想要做的,我犯了一个软按钮并在每一个Android设备的默认软键这个数据发送类型的问题,所以我做了这一点,首先我做了一个Intent在我的“ 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 : 然后在第二个活动中,我在“ 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: 然后,在我成功提出请求之后,或者每当我想告诉“ A”活动此工作成功完成时,都将resultCode的值更改为我在“ A” Activity所说的值,在我的情况下为“ 60”接着:

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. PS:请记住删除Super如果你想为此才能正常工作从onBackPressed方法。

then I should call the onActivityResult Method in my "A" Activity as well: 那么我也应该在“ A”活动中调用onActivityResult方法:

   @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; #HappyCoding;

2021 After the new update in java: 2021年java新更新后:

Use activityresultlauncher() instead of startactivityforresult() in the MainActivity.在 MainActivity 中使用 activityresultlauncher() 而不是 startactivityforresult()。

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():在 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): SecondActivity 内部(onCreate 外部):

@Override
public void onBackPressed() {
    String data = myEditText.getText().toString();
    Intent intent = new Intent();
    intent.putExtra("MyData", data);
    setResult(123, intent);
    finish();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将第1个活动的值传递给android中的第2个活动 - Pass the value from 1st activity to 2nd activity in android 如何在不按后退按钮和关闭按钮的情况下将数据从第二个活动传递到第一个(弹出窗口)? - How to pass data from 2nd activity to 1st (Popup) without press back button and close button? 如何从第二活动到第一活动获取数据 - How to get data from 2nd Activity to 1st Activity 从第一个活动转到第二个活动时出错 - error when going from 1st activity to 2nd activity 当我返回到第一个活动时,第二个活动未调用第二个活动的onCreate()函数 - When I return back to 1st Activity the onCreate() function of 2nd Activity is not called in 2nd time 从Android中的第一个应用程序开始第二个应用程序的活动 - Start Activity of 2nd app from 1st app in android Android:从第二项活动切换回第一项会同时退出 - Android: Switching from 2nd activity back to 1st quits both 如何保存从第一个活动传递到第二个活动的意图数据 - how to save intent data passed from 1st activity to 2nd activity 第一项活动第二项活动获得纬度经度地理位置。 如何将信息转移回第一活动? - 1st activity 2nd activity to get the latitude longitude geo-location. How to transfer info back to 1st activity? 如何在第一个活动中调用第二个活动值? - how to call 2nd activity value in 1st activity?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM