我有一个场景,在通过登录页面登录后,每个活动都会有一个注销按钮。
单击注销时,我将传递要注销的登录用户的会话id。有人能指导我如何让所有活动都可以使用会话id吗?
本案的任何替代方案
我有一个场景,在通过登录页面登录后,每个活动都会有一个注销按钮。
单击注销时,我将传递要注销的登录用户的会话id。有人能指导我如何让所有活动都可以使用会话id吗?
本案的任何替代方案
当前回答
科特林
从第一个活动传递
val intent = Intent(this, SecondActivity::class.java)
intent.putExtra("key", "value")
startActivity(intent)
参加第二项活动
val value = intent.getStringExtra("key")
建议
始终将密钥放在常量文件中,以便于管理。
companion object {
val KEY = "key"
}
其他回答
/*
* If you are from transferring data from one class that doesn't
* extend Activity, then you need to do something like this.
*/
public class abc {
Context context;
public abc(Context context) {
this.context = context;
}
public void something() {
context.startactivity(new Intent(context, anyone.class).putextra("key", value));
}
}
通过捆绑对象从此活动传递参数启动另一个活动
Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("USER_NAME", "xyz@gmail.com");
startActivity(intent);
检索其他活动(YourActivity)
String s = getIntent().getStringExtra("USER_NAME");
这适用于简单类型的数据类型。但如果您想在活动之间传递复杂的数据,则需要首先对其进行序列化。
这里有员工模型
class Employee{
private String empId;
private int age;
print Double salary;
getters...
setters...
}
您可以使用google提供的Gson-lib来序列化复杂的数据这样地
String strEmp = new Gson().toJson(emp);
Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("EMP", strEmp);
startActivity(intent);
Bundle bundle = getIntent().getExtras();
String empStr = bundle.getString("EMP");
Gson gson = new Gson();
Type type = new TypeToken<Employee>() {
}.getType();
Employee selectedEmp = gson.fromJson(empStr, type);
活动之间的数据传递主要通过意向对象进行。
首先,必须使用Bundle类将数据附加到intent对象。然后使用startActivity()或startActivityForResult()方法调用活动。
您可以从博客文章“将数据传递给活动”中找到更多信息。
我在类中使用静态字段,并获取/设置它们:
喜欢:
public class Info
{
public static int ID = 0;
public static String NAME = "TEST";
}
要获取值,请在“活动”中使用:
Info.ID
Info.NAME
要设置值:
Info.ID = 5;
Info.NAME = "USER!";
您可以使用intent类在Activities之间发送数据。它基本上是一条发送给操作系统的消息,您可以在其中描述数据流的源和目的地。类似于从A到B活动的数据。
在活动A(源)中:
Intent intent = new Intent(A.this, B.class);
intent.putExtra("KEY","VALUE");
startActivity(intent);
在活动B(目标)->
Intent intent =getIntent();
String data =intent.getString("KEY");
在这里,您将获得密钥“key”的数据
为了更好地使用,为了简单起见,密钥应该存储在类中,这将有助于将键入错误的风险降至最低
这样地:
public class Constants{
public static String KEY="KEY"
}
现在在活动A中:
intent.putExtra(Constants.KEY,"VALUE");
在活动B中:
String data =intent.getString(Constants.KEY);