在安卓中,如何在不同活动(Activity)之间传递数据?

huangapple go评论86阅读模式
英文:

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

问题

我有两个需要使用意图在彼此之间传递数据的活动。但我不确定应该在哪些地方放置一些 put 和 get 操作。

对于 Activity1(MainActivity),我有一个按钮,按下按钮时会创建一个意图,然后将其放入 Activity2,然后使用 startActivity(intent) 启动 Activity2。

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

然后在 Activity2 中,我在 onCreate() 函数中使用 getIntent 获取那些信息。

现在我想在 Activity2 中放置一个按钮,用于将数据传递给 Activity1,但不一定会“启动/显示”该活动。

所以我想知道如何做到这一点。

我的想法是与之前类似:

Activity2:

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

但我对两件事感到困惑:

  1. 我是否可以在不立即启动活动的情况下完成这个操作?
  2. 在 MainActivity 中我应该在哪里调用 getIntent 来检索这些数据?
英文:

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).

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.

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.

So I'm wondering how this can be done.

My idea is to have the following similar to before:

Activity2:

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

答案1

得分: 3

// 在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();
// 完整的Activity 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");
            }
        }
    }
}
// 完整的Activity 2代码
public class Activity2 extends AppCompatActivity {

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

        if(getIntent().getExtras() != null) {
            // 从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 use startActivityForResult to start Activity2 and receive a result back to 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:

 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:

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();
        });
    }
}

答案2

得分: 0

例如,您可以在activity2中创建一个列表,将要传递给activity1的数据添加到该列表中。在启动activity1之前,您可以从数组中取出这些值,并将它们作为附加项添加到输入中。
您可以将数据添加到JSONObject中,并使用序列化程序,这样您就不必自己添加所有项目。

如果您想在不启动activity1的情况下将数据传递给它,以便activity1处理数据,则不可能。当您在activity2中时,activity不会执行任何操作,对于这种情况,您可以使用片段。

如果您使用片段,您可以将所有数据放入与activity绑定的viewmodel中,而不是放入每个片段中。

英文:

You can for example create a list in activity2 to which you add the data you want to pass to activity1. Before starting activity1 you get the values out of your array and add them as extras to the input.
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.

If you want to pass your data to activity1 without starting it,so activity1 processes the data, that is not possible. Activity doesnt execute anything while you are in activity2, for such cases you use fragments.

If you use fragments you can put all data in a viewmodel which is bound to the activity instead of each fragment.

答案3

得分: 0

有几种方法可以实现这个,具体取决于您要传递的数据类型。

如果是整个类对象,那么可以使类可被Parcel化。您可以将类复制粘贴到此网站http://www.parcelabler.com/中,它会自动为您格式化。您只需要将其作为意图附加项传递。

如果您要处理需要执行操作然后传递到另一个活动的数据,我建议使用意图服务(Intent Service)。您可以根据服务接收到的意图执行某些操作。

如果您只想在应用程序中发生了XYZ事件后执行特定操作,那么请使用共享首选项(Shared Preferences)。这些可以很容易地在任何地方访问。

最后,如果您持续使用大量需要保持持久性的数据,可以使用本地数据库存储,并在需要时进行查询。

英文:

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. 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. 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.

答案4

得分: -1

你可以使用SharedPreferences 或静态变量/字段来实现这个。

英文:

You can use SharedPreferences or static variables/fields for that.

huangapple
  • 本文由 发表于 2020年10月20日 05:04:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/64435071.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定