简体   繁体   English

你如何在 Android 的活动之间来回传递数据?

[英]How do you pass data back and forth between activities in Android?

I have two activities that should pass data back and forth to each other using intents.我有两个活动应该使用意图来回传递数据。 I'm not sure where to place some of the puts and gets though.我不确定在哪里放置一些看跌期权。

For Activity1 (MainActivity), I have a button, and on press it creates an intent, and then puts it to Activity2, then starts it using startActivity(intent).对于 Activity1 (MainActivity),我有一个按钮,按下它会创建一个意图,然后将其放入 Activity2,然后使用 startActivity(intent) 启动它。

btn.setOnClickListener((v) -> {
    Intent intent = new Intent(this, Activity2.class);
    intent.putExtra("test", testClass);
    startActivity(intent);
});

Then in Activity2, I get that information in the onCreate() function using getIntent.然后在 Activity2 中,我使用 getIntent 在 onCreate() 函数中获取该信息。

Now what I want to do is have a button in Activity2 that will pass data to Activity1, but won't necessarily "start/show" the activity.现在我想要做的是在 Activity2 中有一个按钮,它将数据传递给 Activity1,但不一定“启动/显示”活动。

So I'm wondering how this can be done.所以我想知道如何做到这一点。

My idea is to have the following similar to before:我的想法是具有与以前类似的以下内容:

Activity2:活动2:

btn.setOnClickListener((v) -> {
    Intent intent = new Intent(this, MainActivity.class);
    intent.putExtra("info", info);
});

But I'm confused about two things但我对两件事感到困惑

  1. Can I do this without starting the activity right away我可以在不立即开始活动的情况下执行此操作吗
  2. Where would I do the getIntent call in MainActivity to retrieve this data我在哪里可以在 MainActivity 中调用 getIntent 来检索这些数据

You can use startActivityForResult to start Activity2 and receive a result back to Activity1您可以使用startActivityForResult来启动Activity2并接收返回给Activity1的结果

Activity 1活动一

int LAUNCH_ACTIVITY_TWO = 1;
Intent i = new Intent(this, Activity2.class);
i.putExtra("test", testClass);
startActivityForResult(i, LAUNCH_ACTIVITY_TWO);

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

    if (requestCode == LAUNCH_ACTIVITY_TWO) {
        if(resultCode == Activity.RESULT_OK){
            String result=data.getStringExtra("result");
        }
    }
}

Activity 2活动二

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

Full Activity 1 code:完整活动 1 代码:

 public class MainActivity extends AppCompatActivity {
    public static int LAUNCH_ACTIVITY_TWO = 1;

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

        Button btn = (Button) findViewById(R.id.btn);

        btn.setOnClickListener((v) -> {
            Intent i = new Intent(this, Activity2.class);
            i.putExtra("test", testClass);
            startActivityForResult(i, LAUNCH_ACTIVITY_TWO);
        });
    }

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

        if (requestCode == LAUNCH_ACTIVITY_TWO) {
            if(resultCode == Activity.RESULT_OK){
                String result= data.getStringExtra("result");
            }
        }
    }
}

Full Activity 2 code:完整活动 2 代码:

public class Activity2 extends AppCompatActivity {

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

        if(getIntent().getExtras() != null) {
            // Get intent extras from Activity 1
        }
        
        Button btn = (Button) findViewById(R.id.btn);

        btn.setOnClickListener((v) -> {
            Intent returnIntent = new Intent();
            returnIntent.putExtra("result", result);
            setResult(Activity.RESULT_OK, returnIntent);
            finish();
        });
    }
}

You can for example create a list in activity2 to which you add the data you want to pass to activity1.例如,您可以在活动 2 中创建一个列表,向其中添加要传递给活动 1 的数据。 Before starting activity1 you get the values out of your array and add them as extras to the input.在开始 activity1 之前,您从数组中取出值并将它们作为附加值添加到输入中。 You can have the data added to a JSONObject and use a serializer so you don't have to add your items all by yourself.您可以将数据添加到 JSONObject 并使用序列化程序,这样您就不必自己添加所有项目。

If you want to pass your data to activity1 without starting it,so activity1 processes the data, that is not possible.如果您想在不启动的情况下将数据传递给活动 1,那么活动 1 处理数据,这是不可能的。 Activity doesnt execute anything while you are in activity2, for such cases you use fragments.当您处于活动 2 中时,活动不会执行任何操作,对于这种情况,您使用片段。

If you use fragments you can put all data in a viewmodel which is bound to the activity instead of each fragment.如果您使用片段,您可以将所有数据放在绑定到活动而不是每个片段的视图模型中。

There are several ways you can achieve this pending on what type of data you're looking at passing.有几种方法可以实现这一点,具体取决于您正在查看传递的数据类型。

If it's an entire class object then make the class parcable.如果它是一个完整的类对象,那么使类可解析。 You can copy and paste the class in this website http://www.parcelabler.com/ and it auto formats it for you.您可以将课程复制并粘贴到此网站http://www.parcelabler.com/ 中,它会自动为您设置格式。 All you do is pass it as an intent extra.你所做的就是将它作为一个额外的意图传递。

If you're looking at data that needs an action performed on it and then passed to another activity I would suggest using and intent service.如果您正在查看需要对其执行操作然后传递给另一个活动的数据,我建议使用和意图服务。 You can perform certain actions pending the intents received in the service.您可以在等待服务中收到的意图之前执行某些操作。

If you're looking at performing certain actions only after XYZ has occurred in your application then used shared preferences.如果您希望仅在应用程序中发生 XYZ 后执行某些操作,则使用共享首选项。 These can be accessed anywhere quite easily.这些可以很容易地在任何地方访问。

Lastly, if you're using bulk data consistently that needs to remain persistent, use a local database storage and just query when you need to.最后,如果您持续使用需要保持持久性的批量数据,请使用本地数据库存储并在需要时进行查询。

您可以为此使用SharedPreferences或静态变量/字段。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM