如何在 Android 应用程序中的活动之间传递数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2091465/
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
How do I pass data between Activities in Android application?
提问by UMAR
I have a scenario where, after logging in through a login page, there will be a sign-out button
on each activity
.
我有一个场景,在通过登录页面登录后button
,每个activity
.
On clicking sign-out
, I will be passing the session id
of the signed in user to sign-out. Can anyone guide me on how to keep session id
available to all activities
?
单击 时sign-out
,我将传递session id
已登录用户的 以退出。谁能指导我如何让session id
所有人都可以使用activities
?
Any alternative to this case
这种情况的任何替代方案
采纳答案by Erich Douglass
The easiest way to do this would be to pass the session id to the signout activity in the Intent
you're using to start the activity:
最简单的方法是将会话 ID 传递给Intent
您用来启动活动的注销活动:
Intent intent = new Intent(getBaseContext(), SignoutActivity.class);
intent.putExtra("EXTRA_SESSION_ID", sessionId);
startActivity(intent);
Access that intent on next activity:
访问下一个活动的意图:
String sessionId = getIntent().getStringExtra("EXTRA_SESSION_ID");
The docsfor Intents has more information (look at the section titled "Extras").
Intents的文档有更多信息(查看标题为“Extras”的部分)。
回答by user914425
In your current Activity, create a new Intent
:
在您当前的活动中,创建一个新的Intent
:
String value="Hello world";
Intent i = new Intent(CurrentActivity.this, NewActivity.class);
i.putExtra("key",value);
startActivity(i);
Then in the new Activity, retrieve those values:
然后在新的 Activity 中,检索这些值:
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("key");
//The key argument here must match that used in the other activity
}
Use this technique to pass variables from one Activity to the other.
使用此技术将变量从一个活动传递到另一个活动。
回答by Charlie Collins
Passing Intentextras is a good approach as Erich noted.
正如 Erich 指出的那样,传递Intentextras 是一个很好的方法。
The Applicationobject is another way though, and it is sometimes easier when dealing with the same state across multiple activities (as opposed to having to get/put it everywhere), or objects more complex than primitives and Strings.
该应用对象是另一种方式,虽然,跨多个活动相同的状态打交道时(而不是让获得/把它无处不在),有时更容易,或者比的对象原语和字符串更加复杂。
You can extend Application, and then set/get whatever you want there and access it from any Activity (in the same application) with getApplication().
您可以扩展应用程序,然后在那里设置/获取您想要的任何内容,并使用getApplication()从任何活动(在同一应用程序中)访问它。
Also keep in mind that other approaches you might see, like statics, can be problematic because they can lead to memory leaks. Application helps solve this too.
还请记住,您可能会看到的其他方法(例如静态方法)可能存在问题,因为它们会导致内存泄漏。应用程序也有助于解决这个问题。
回答by Md. Rahman
Source class:
源类:
Intent myIntent = new Intent(this, NewActivity.class);
myIntent.putExtra("firstName", "Your First Name Here");
myIntent.putExtra("lastName", "Your Last Name Here");
startActivity(myIntent)
Destination Class (NewActivity class):
目标类(NewActivity 类):
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
Intent intent = getIntent();
String fName = intent.getStringExtra("firstName");
String lName = intent.getStringExtra("lastName");
}
回答by Mayank Saini
You just have to send extras while calling your intent.
你只需要在调用你的意图时发送额外的内容。
Like this:
像这样:
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
intent.putExtra("Variable name", "Value you want to pass");
startActivity(intent);
Now on the OnCreate
method of your SecondActivity
you can fetch the extras like this.
现在在你的OnCreate
方法上,SecondActivity
你可以像这样获取额外的东西。
If the value you sent was in long
:
如果您发送的值在long
:
long value = getIntent().getLongExtra("Variable name which you sent as an extra", defaultValue(you can give it anything));
If the value you sent was a String
:
如果您发送的值为String
:
String value = getIntent().getStringExtra("Variable name which you sent as an extra");
If the value you sent was a Boolean
:
如果您发送的值为Boolean
:
Boolean value = getIntent().getBooleanExtra("Variable name which you sent as an extra", defaultValue);
回答by Suragch
It helps me to see things in context. Here are two examples.
它帮助我在上下文中看待事物。这里有两个例子。
Passing Data Forward
向前传递数据
Main Activity
主要活动
- Put the data you want to send in an Intent with a key-value pair. See this answerfor naming conventions for the key.
- Start the Second Activity with
startActivity
.
- 将您要发送的数据放入具有键值对的 Intent 中。请参阅此答案以了解密钥的命名约定。
- 用 开始第二个活动
startActivity
。
MainActivity.java
主活动.java
public class MainActivity extends AppCompatActivity {
@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) {
// get the text to pass
EditText editText = (EditText) findViewById(R.id.editText);
String textToPass = editText.getText().toString();
// start the SecondActivity
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra(Intent.EXTRA_TEXT, textToPass);
startActivity(intent);
}
}
Second Activity
第二个活动
- You use
getIntent()
to get theIntent
that started the second activity. Then you can extract the data withgetExtras()
and the key you defined in the first activity. Since our data is a String we will just usegetStringExtra
here.
- 您
getIntent()
用来获取Intent
启动第二个活动的 。然后,您可以使用getExtras()
您在第一个活动中定义的密钥提取数据。由于我们的数据是一个字符串,我们将在getStringExtra
这里使用。
SecondActivity.java
第二个Activity.java
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
// get the text from MainActivity
Intent intent = getIntent();
String text = intent.getStringExtra(Intent.EXTRA_TEXT);
// use the text in a TextView
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(text);
}
}
Passing Data Back
回传数据
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 result 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. I could use any string for the key but I'll use the predefinedIntent.EXTRA_TEXT
since I'm sending text.
- 使用 启动第二个活动
startActivityForResult
,为其提供任意结果代码。 - 覆盖
onActivityResult
。这在第二个活动完成时调用。您可以通过检查结果代码来确保它实际上是第二个活动。(当您从同一个主要活动开始多个不同的活动时,这很有用。) - 提取您从 return 中获得的数据
Intent
。使用键值对提取数据。我可以使用任何字符串作为键,但我将使用预定义的,Intent.EXTRA_TEXT
因为我正在发送文本。
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(Intent.EXTRA_TEXT);
// 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 theIntent
using a key-value pair. I chose to useIntent.EXTRA_TEXT
for my key. - Set the result to
RESULT_OK
and add the intent holding your data. - Call
finish()
to close the Second Activity.
- 将要发送回上一个活动的数据放入
Intent
. 数据存储在Intent
使用键值对中。我选择Intent.EXTRA_TEXT
用于我的钥匙。 - 将结果设置为
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(Intent.EXTRA_TEXT, stringToPassBack);
setResult(RESULT_OK, intent);
finish();
}
}
回答by angryITguy
UpdatedNote that I had mentioned the use of SharedPreference. It has a simple API and is accessible across an application's activities. But this is a clumsy solution, and is a security risk if you pass around sensitive data. It's best to use intents. It has an extensive list of overloaded methods that can be used to better transfer many different data types between activities. Have a look at intent.putExtra. This linkpresents the use of putExtra quite well.
更新请注意,我已经提到了SharedPreference的使用。它有一个简单的 API,可以跨应用程序的活动访问。但这是一个笨拙的解决方案,如果您传递敏感数据,则存在安全风险。最好使用意图。它有一个广泛的重载方法列表,可用于在活动之间更好地传输许多不同的数据类型。看看intent.putExtra。这个链接很好地展示了 putExtra 的使用。
In passing data between activities, my preferred approach is to create a static method for the relevant activity that includes the required parameters launch the intent. Which then provides easily setup and retrieve parameters. So it can look like this
在活动之间传递数据时,我的首选方法是为相关活动创建一个静态方法,其中包括启动意图所需的参数。然后提供轻松设置和检索参数。所以它看起来像这样
public class MyActivity extends Activity {
public static final String ARG_PARAM1 = "arg_param1";
...
public static getIntent(Activity from, String param1, Long param2...) {
Intent intent = new Intent(from, MyActivity.class);
intent.putExtra(ARG_PARAM1, param1);
intent.putExtra(ARG_PARAM2, param2);
return intent;
}
....
// Use it like this.
startActivity(MyActvitiy.getIntent(FromActivity.this, varA, varB, ...));
...
Then you can create an intent for the intended activity and ensure you have all the parameters. You can adapt for fragments to. A simple example above, but you get the idea.
然后,您可以为预期活动创建意图并确保您拥有所有参数。你可以适应片段。上面是一个简单的例子,但你明白了。
回答by ponkin
Try to do the following:
尝试执行以下操作:
Create a simple "helper" class (factory for your Intents), like this:
创建一个简单的“helper”类(为您的 Intent 工厂),如下所示:
import android.content.Intent;
public class IntentHelper {
public static final Intent createYourSpecialIntent(Intent src) {
return new Intent("YourSpecialIntent").addCategory("YourSpecialCategory").putExtras(src);
}
}
This will be the factory for all your Intents. Everytime you need a new Intent, create a static factory method in IntentHelper. To create a new Intent you should just say it like this:
这将是您所有意图的工厂。每次需要新的 Intent 时,请在 IntentHelper 中创建一个静态工厂方法。要创建一个新的 Intent,你应该这样说:
IntentHelper.createYourSpecialIntent(getIntent());
In your activity. When you want to "save" some data in a "session" just use the following:
在你的活动中。当您想在“会话”中“保存”一些数据时,只需使用以下命令:
IntentHelper.createYourSpecialIntent(getIntent()).putExtra("YOUR_FIELD_NAME", fieldValueToSave);
And send this Intent. In the target Activity your field will be available as:
并发送此 Intent。在目标活动中,您的字段将显示为:
getIntent().getStringExtra("YOUR_FIELD_NAME");
So now we can use Intent like same old session (like in servlets or JSP).
所以现在我们可以像旧会话一样使用 Intent(比如在 servlets 或JSP 中)。
回答by Vaibhav Sharma
You can also pass custom class objects by making a parcelableclass. Best way to make it parcelable is to write your class and then simply paste it to a site like http://www.parcelabler.com/. Click on build and you will get new code. Copy all of this and replace the original class contents. Then-
您还可以通过创建可打包的类来传递自定义类对象。使其可打包的最佳方法是编写您的类,然后将其粘贴到像http://www.parcelabler.com/这样的站点。单击构建,您将获得新代码。复制所有这些并替换原来的类内容。然后-
Intent intent = new Intent(getBaseContext(), NextActivity.class);
Foo foo = new Foo();
intent.putExtra("foo", foo);
startActivity(intent);
and get the result in NextActivity like-
并在 NextActivity 中获得结果,例如-
Foo foo = getIntent().getExtras().getParcelable("foo");
Now you can simply use the fooobject like you would have used.
现在您可以像以前一样简单地使用foo对象。
回答by ComputerSaysNo
Another way is to use a public static field in which you store data, i.e.:
另一种方法是使用存储数据的公共静态字段,即:
public class MyActivity extends Activity {
public static String SharedString;
public static SomeObject SharedObject;
//...