将数据发送回 Android 中的 Main Activity

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/920306/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 02:30:44  来源:igfitidea点击:

Sending data back to the Main Activity in Android

androidandroid-intent

提问by Rajapandian

I have two activities: main activity and child activity.
When I press a button in the main activity, the child activity is launched.

我有两个活动:主要活动和子活动。
当我按下主活动中的按钮时,子活动就会启动。

Now I want to send some data back to the main screen. I used the Bundle class, but it is not working. It throws some runtime exceptions.

现在我想将一些数据发送回主屏幕。我使用了 Bundle 类,但它不起作用。它会抛出一些运行时异常。

Is there any solution for this?

有什么解决办法吗?

回答by Reto Meier

There are a couple of ways to achieve what you want, depending on the circumstances.

根据具体情况,有几种方法可以实现您想要的目标。

The most common scenario (which is what yours sounds like) is when a child Activity is used to get user input - such as choosing a contact from a list or entering data in a dialog box. In this case you should use startActivityForResultto launch your child Activity.

最常见的情况(这就是您的情况)是当子活动用于获取用户输入时 - 例如从列表中选择联系人或在对话框中输入数据。在这种情况下,您应该使用startActivityForResult来启动您的子活动。

This provides a pipeline for sending data back to the main Activity using setResult. The setResult method takes an int result value and an Intent that is passed back to the calling Activity.

这提供了使用 将数据发送回主活动的管道setResult。setResult 方法采用 int 结果值和传递回调用 Activity 的 Intent。

Intent resultIntent = new Intent();
// TODO Add extras or a data URI to this intent as appropriate.
resultIntent.putExtra("some_key", "String data"); 
setResult(Activity.RESULT_OK, resultIntent);
finish();

To access the returned data in the calling Activity override onActivityResult. The requestCode corresponds to the integer passed in in the startActivityForResultcall, while the resultCode and data Intent are returned from the child Activity.

在调用 Activity override 中访问返回的数据onActivityResult。requestCode对应的是startActivityForResult调用中传入的整数,而resultCode和数据Intent则是从子Activity返回的。

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
  switch(requestCode) {
    case (MY_CHILD_ACTIVITY) : {
      if (resultCode == Activity.RESULT_OK) {
        // TODO Extract the data returned from the child Activity.
        String returnValue = data.getStringExtra("some_key");
      }
      break;
    } 
  }
}

回答by jimmithy

Activity 1 uses startActivityForResult:

活动 1 使用startActivityForResult

startActivityForResult(ActivityTwo, ActivityTwoRequestCode);

Activity 2 is launched and you can perform the operation, to close the Activity do this:

Activity 2 被启动,你可以执行操作,要关闭 Activity 这样做:

Intent output = new Intent();
output.putExtra(ActivityOne.Number1Code, num1);
output.putExtra(ActivityOne.Number2Code, num2);
setResult(RESULT_OK, output);
finish();

Activity 1 - returning from the previous activity will call onActivityResult:

活动 1 - 从前一个活动返回将调用onActivityResult

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == ActivityTwoRequestCode && resultCode == RESULT_OK && data != null) {
        num1 = data.getIntExtra(Number1Code);
        num2 = data.getIntExtra(Number2Code);
    }
}

UPDATE: Answer to Seenu69's comment, In activity two,

更新:回答 Seenu69 的评论,在活动二中,

int result = Integer.parse(EditText1.getText().toString()) 
           + Integer.parse(EditText2.getText().toString());
output.putExtra(ActivityOne.KEY_RESULT, result);

Then in activity one,

然后在活动一中,

int result = data.getExtra(KEY_RESULT);

回答by Suragch

Sending Data Back

发回数据

It helps me to see things in context. Here is a complete simple project for sending data back. Rather than providing the xml layout files, here is an image.

它帮助我在上下文中看待事物。这是一个完整的简单项目,用于发送数据。这里没有提供 xml 布局文件,而是一个图像。

enter image description here

在此处输入图片说明

Main Activity

主要活动

  • Start the Second Activity with startActivityForResult, providing it an arbitrary result code.
  • Override onActivityResult. This is called when the Second Activity finishes. You can make sure that it is actually the Second Activity by checking the request code. (This is useful when you are starting multiple different activities from the same main activity.)
  • Extract the data you got from the return Intent. The data is extracted using a key-value pair.
  • 使用 启动第二个活动startActivityForResult,为其提供任意结果代码。
  • 覆盖onActivityResult。这在第二个活动完成时调用。您可以通过检查请求代码来确保它实际上是第二个活动。(当您从同一个主要活动开始多个不同的活动时,这很有用。)
  • 提取您从 return 中获得的数据Intent。使用键值对提取数据。

MainActivity.java

主活动.java

public class MainActivity extends AppCompatActivity {

    private static final int SECOND_ACTIVITY_REQUEST_CODE = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    // "Go to Second Activity" button click
    public void onButtonClick(View view) {

        // Start the SecondActivity
        Intent intent = new Intent(this, SecondActivity.class);
        startActivityForResult(intent, SECOND_ACTIVITY_REQUEST_CODE);
    }

    // This method is called when the second activity finishes
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // Check that it is the SecondActivity with an OK result
        if (requestCode == SECOND_ACTIVITY_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {

                // Get String data from Intent
                String returnString = data.getStringExtra("keyName");

                // Set text view with string
                TextView textView = (TextView) findViewById(R.id.textView);
                textView.setText(returnString);
            }
        }
    }
}

Second Activity

第二个活动

  • Put the data that you want to send back to the previous activity into an Intent. The data is stored in the Intentusing a key-value pair.
  • Set the result to RESULT_OKand add the intent holding your data.
  • Call finish()to close the Second Activity.
  • 将要发送回上一个活动的数据放入Intent. 数据存储在Intent使用键值对中。
  • 将结果设置为RESULT_OK并添加保存数据的意图。
  • 调用finish()以关闭第二个活动。

SecondActivity.java

第二个Activity.java

public class SecondActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
    }

    // "Send text back" button click
    public void onButtonClick(View view) {

        // Get the text from the EditText
        EditText editText = (EditText) findViewById(R.id.editText);
        String stringToPassBack = editText.getText().toString();

        // Put the String to pass back into an Intent and close this activity
        Intent intent = new Intent();
        intent.putExtra("keyName", stringToPassBack);
        setResult(RESULT_OK, intent);
        finish();
    }
}

Other notes

其他注意事项

  • If you are in a Fragment it won't know the meaning of RESULT_OK. Just use the full name: Activity.RESULT_OK.
  • 如果您在 Fragment 中,它将不知道RESULT_OK. 只需使用全名:Activity.RESULT_OK.

See also

也可以看看

回答by Vijay

FirstActivity uses startActivityForResult:

FirstActivity 使用 startActivityForResult:

Intent intent = new Intent(MainActivity.this,SecondActivity.class);
startActivityForResult(intent, int resultCode); // suppose resultCode == 2

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 2)
    {
        String message=data.getStringExtra("MESSAGE");
    }
}

On SecondActivity call setResult() onClick events or onBackPressed()

在 SecondActivity 调用 setResult() onClick 事件或 onBackPressed()

Intent intent=new Intent();
intent.putExtra("MESSAGE",message);
setResult(Activity.RESULT_OK, intent);

回答by Intrications

Call the child activity Intent using the startActivityForResult() method call

使用 startActivityForResult() 方法调用调用子活动 Intent

There is an example of this here: http://developer.android.com/training/notepad/notepad-ex2.html

这里有一个例子:http: //developer.android.com/training/notepad/notepad-ex2.html

and in the "Returning a Result from a Screen" of this: http://developer.android.com/guide/faq/commontasks.html#opennewscreen

并在“从屏幕返回结果”中:http: //developer.android.com/guide/faq/commontasks.html#opennewscreen

回答by Kuls

I have created simple demo class for your better reference.

我创建了简单的演示类供您更好地参考。

FirstActivity.java

第一活动.java

 public class FirstActivity extends AppCompatActivity {

    private static final String TAG = FirstActivity.class.getSimpleName();
    private static final int REQUEST_CODE = 101;
    private Button btnMoveToNextScreen;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnMoveToNextScreen = (Button) findViewById(R.id.btnMoveToNext);
        btnMoveToNextScreen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent mIntent = new Intent(FirstActivity.this, SecondActivity.class);
                startActivityForResult(mIntent, REQUEST_CODE);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(resultCode == RESULT_OK){
            if(requestCode == REQUEST_CODE && data !=null) {
                String strMessage = data.getStringExtra("keyName");
                Log.i(TAG, "onActivityResult: message >>" + strMessage);
            }
        }

    }
}

And here is SecondActivity.java

这是 SecondActivity.java

public class SecondActivity extends AppCompatActivity {

    private static final String TAG = SecondActivity.class.getSimpleName();
    private Button btnMoveToPrevious;
    private EditText editText;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        editText = (EditText) findViewById(R.id.editText);

        btnMoveToPrevious = (Button) findViewById(R.id.btnMoveToPrevious);
        btnMoveToPrevious.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String message = editText.getEditableText().toString();

                Intent mIntent = new Intent();
                mIntent.putExtra("keyName", message);
                setResult(RESULT_OK, mIntent);
                finish();

            }
        });

    }
}

回答by Yogesh Adhe

In first activity u can send intent using startActivityForResult()and then get result from second activity after it finished using setResult.

在第一个活动中,您可以使用发送意图 startActivityForResult(),然后在使用完后从第二个活动中获取结果setResult

MainActivity.class

主Activity.class

public class MainActivity extends AppCompatActivity {

    private static final int SECOND_ACTIVITY_RESULT_CODE = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    // "Go to Second Activity" button click
    public void onButtonClick(View view) {

        // Start the SecondActivity
        Intent intent = new Intent(this, SecondActivity.class);
        // send intent for result 
        startActivityForResult(intent, SECOND_ACTIVITY_RESULT_CODE);
    }

    // This method is called when the second activity finishes
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // check that it is the SecondActivity with an OK result
        if (requestCode == SECOND_ACTIVITY_RESULT_CODE) {
            if (resultCode == RESULT_OK) {

                // get String data from Intent
                String returnString = data.getStringExtra("keyName");

                // set text view with string
                TextView textView = (TextView) findViewById(R.id.textView);
                textView.setText(returnString);
            }
        }
    }
}

SecondActivity.class

第二个Activity.class

public class SecondActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
    }

    // "Send text back" button click
    public void onButtonClick(View view) {

        // get the text from the EditText
        EditText editText = (EditText) findViewById(R.id.editText);
        String stringToPassBack = editText.getText().toString();

        // put the String to pass back into an Intent and close this activity
        Intent intent = new Intent();
        intent.putExtra("keyName", stringToPassBack);
        setResult(RESULT_OK, intent);
        finish();
    }
}

回答by Shivam Yadav

All these answers are explaining the scenario of your second activity needs to be finish after sending the data.

所有这些答案都解释了发送数据后需要完成的第二个活动的场景。

But in case if you don't want to finish the second activity and want to send the data back in to first then for that you can use BroadCastReceiver.

但是,如果您不想完成第二个活动并希望将数据发送回第一个,那么您可以使用 BroadCastReceiver。

In Second Activity -

在第二个活动中 -

Intent intent = new Intent("data");
intent.putExtra("some_data", true);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

In First Activity-

在第一个活动中-

private BroadcastReceiver tempReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        // do some action
    }
};

Register the receiver in onCreate()-

在 onCreate() 中注册接收者-

 LocalBroadcastManager.getInstance(this).registerReceiver(tempReceiver,new IntentFilter("data"));

Unregister it in onDestroy()

在 onDestroy() 中取消注册

回答by Lenos

Another way of achieving the desired result which may be better depending on your situation is to create a listener interface.

实现预期结果的另一种方法(根据您的情况可能会更好)是创建一个侦听器界面。

By making the parent activity listen to an interface that get triggered by the child activity while passing the required data as a parameter can create a similar set of circumstance

通过让父 Activity 侦听由子 Activity 触发的接口,同时将所需数据作为参数传递,可以创建一组类似的情况

回答by Dhruv Jagetiya

Just a small detail that I think is missing in above answers.

只是我认为上述答案中缺少的一个小细节。

If your child activity can be opened from multiple parent activities then you can check if you need to do setResultor not, based on if your activity was opened by startActivityor startActivityForResult. You can achieve this by using getCallingActivity(). More info here.

如果您的子活动可以从多个父活动打开,那么您可以setResult根据您的活动是否由startActivity或打开来检查您是否需要这样做startActivityForResult。您可以使用getCallingActivity(). 更多信息在这里