如何在Android应用程序的“活动”之间传递数据?

吃可爱长大的小学妹 提交于 2019-12-09 17:56:46

我有一种情况,在通过登录页面登录后,每个activity上都会有一个退出button

点击sign-out ,我将传递已登录用户的session id以便退出。 谁能指导我如何使session id可供所有activities

这种情况的任何替代方法


#1楼

在活动之间传递数据的最方便方法是传递意图。 在您要发送数据的第一个活动中,应添加代码,

String str = "My Data"; //Data you want to send
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("name",str); //Here you will add the data into intent to pass bw activites
v.getContext().startActivity(intent);

您还应该导入

import android.content.Intent;

然后,在下一个Acitvity(SecondActivity)中,应该使用以下代码从意图中检索数据。

String name = this.getIntent().getStringExtra("name");

#2楼

另一种方法是使用存储数据的公共静态字段,即:

public class MyActivity extends Activity {

  public static String SharedString;
  public static SomeObject SharedObject;

//...

#3楼

活动之间的数据传递主要是通过意图对象进行的。

首先,您必须使用Bundle类将数据附加到意图对象。 然后使用startActivity()startActivityForResult()方法调用活动。

您可以通过博客文章“将数据传递给Activity”中的示例找到有关它的更多信息。


#4楼

我最近发布了Vapor API ,这是一个jQuery风格的Android框架,它使诸如此类的各种任务变得更加简单。 如前所述, SharedPreferences是您可以执行此操作的一种方法。

VaporSharedPreferences被实现为Singleton,因此是一种选择,并且在Vapor API中,它具有重载的.put(...)方法,因此您不必明确担心要提交的数据类型-只要受支持即可。 它也很流利,因此您可以链接呼叫:

$.prefs(...).put("val1", 123).put("val2", "Hello World!").put("something", 3.34);

它还可以选择自动保存更改,并在后台统一读取和写入过程,因此您无需像在标准Android中一样显式地检索Editor。

或者,您可以使用Intent 。 在蒸气API,您还可以使用可链接的重载.put(...)上的方法VaporIntent

$.Intent().put("data", "myData").put("more", 568)...

如其他答案中所述,并将其作为额外的内容传递。 您可以从Activity检索其他内容,此外,如果您使用的是VaporActivity此操作会自动完成,因此您可以使用:

this.extras()

要在“ Activity的另一端检索它们,请切换到。

希望一些人感兴趣:)


#5楼

您只需要在发送意向时发送额外内容。

像这样:

Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
intent.putExtra("Variable name", "Value you want to pass");
startActivity(intent);

现在,在SecondActivityOnCreate方法上,您可以像这样获取其他功能。

如果您发送的值long

long value = getIntent().getLongExtra("Variable name which you sent as an extra", defaultValue(you can give it anything));

如果您发送的值为String

String value = getIntent().getStringExtra("Variable name which you sent as an extra");

如果您发送的值是Boolean

Boolean value = getIntent().getBooleanExtra("Variable name which you sent as an extra", defaultValue);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!