我有一个场景,在通过登录页面登录后,每个活动都会有一个注销按钮。
单击注销时,我将传递要注销的登录用户的会话id。有人能指导我如何让所有活动都可以使用会话id吗?
本案的任何替代方案
我有一个场景,在通过登录页面登录后,每个活动都会有一个注销按钮。
单击注销时,我将传递要注销的登录用户的会话id。有人能指导我如何让所有活动都可以使用会话id吗?
本案的任何替代方案
当前回答
我们可以通过两种方式将值传递给另一个Activity(已经发布了相同类型的答案,但我在这里发布了通过意图尝试的redcing代码)
1.通过意图
Activity1:
startActivity(new Intent(getApplicationContext(),Activity2.class).putExtra("title","values"));
InActivity 2:
String recString= getIntent().getStringExtra("title");
2.通过SharedPreference
Activity1:
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
// 0 - for private mode
Editor editor = pref.edit();
editor.putString("key_name", "string value"); // Storing string
editor.commit(); // commit changes
Activty2:
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
pref.getString("key_name", null); // getting String
其他回答
你只需要在表达你的意图时发送额外的信息。
这样地:
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
intent.putExtra("Variable name", "Value you want to pass");
startActivity(intent);
现在,在SecondActivity的OnCreate方法中,您可以像这样获取额外内容。
如果您发送的值过长:
long value = getIntent().getLongExtra("Variable name which you sent as an extra", defaultValue(you can give it anything));
如果发送的值是字符串:
String value = getIntent().getStringExtra("Variable name which you sent as an extra");
如果发送的值是布尔值:
Boolean value = getIntent().getBooleanExtra("Variable name which you sent as an extra", defaultValue);
您可以使用intent对象在活动之间发送数据。假设您有两个活动,即FirstActivity和SecondActivity。
内部第一活动:
使用意图:
i = new Intent(FirstActivity.this,SecondActivity.class);
i.putExtra("key", value);
startActivity(i)
内部第二活动
Bundle bundle= getIntent().getExtras();
现在,您可以使用不同的bundle类方法获取通过Key从FirstActivity传递的值。
例如。bundle.getString(“key”)、bundle.get-Double(“key“)、bundle.getInt(“key”)等。
正如埃里希指出的那样,传递意图附加是一个好方法。
然而,Application对象是另一种方式,当跨多个活动处理同一状态时(而不是必须在任何地方获取/放置它),或者处理比原语和字符串更复杂的对象时,它有时更容易。
您可以扩展Application,然后使用getApplication()从任何活动(在同一应用程序中)设置/获取所需的内容。
还要记住,您可能看到的其他方法,如静态,可能会有问题,因为它们可能会导致内存泄漏。应用程序也有助于解决这一问题。
来自活动
int n= 10;
Intent in = new Intent(From_Activity.this,To_Activity.class);
Bundle b1 = new Bundle();
b1.putInt("integerNumber",n);
in.putExtras(b1);
startActivity(in);
目标活动
Bundle b2 = getIntent().getExtras();
int m = 0;
if(b2 != null){
m = b2.getInt("integerNumber");
}
我最近发布了Vapor API,这是一个jQuery风格的Android框架,它使类似这样的所有任务都更加简单。如前所述,SharedPreferences是实现此目的的一种方法。
VaporSharedPreferences实现为Singleton,因此这是一个选项,在VaporAPI中,它有一个重载的.put(…)方法,因此您不必明确担心您提交的数据类型-前提是它受支持。它也很流畅,因此您可以拨打电话:
$.prefs(...).put("val1", 123).put("val2", "Hello World!").put("something", 3.34);
它还可以选择自动保存更改,并在后台统一读写过程,因此您不需要像在标准Android中那样显式检索编辑器。
或者,您可以使用意向。在VaporAPI中,您还可以对VaporContent使用可链接的overload.put(…)方法:
$.Intent().put("data", "myData").put("more", 568)...
如其他答案中所述,将其作为附加项传递。您可以从“活动”中检索额外内容,此外,如果您正在使用VaporActivity,这将自动为您完成,因此您可以使用:
this.extras()
要在切换到的“活动”的另一端检索它们。
希望有人对此感兴趣:)