我有一个场景,在通过登录页面登录后,每个活动都会有一个注销按钮。
单击注销时,我将传递要注销的登录用户的会话id。有人能指导我如何让所有活动都可以使用会话id吗?
本案的任何替代方案
我有一个场景,在通过登录页面登录后,每个活动都会有一个注销按钮。
单击注销时,我将传递要注销的登录用户的会话id。有人能指导我如何让所有活动都可以使用会话id吗?
本案的任何替代方案
当前回答
您可以使用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);
其他回答
我在类中使用静态字段,并获取/设置它们:
喜欢:
public class Info
{
public static int ID = 0;
public static String NAME = "TEST";
}
要获取值,请在“活动”中使用:
Info.ID
Info.NAME
要设置值:
Info.ID = 5;
Info.NAME = "USER!";
在当前活动中创建新的意向。
String myData="Your string/data here";
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("your_key",myData);
startActivity(intent);
在SecondActivity.java onCreate()中使用键your_key检索这些值
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String myData = extras.getString("your_key");
}
}
源类:
Intent myIntent = new Intent(this, NewActivity.class);
myIntent.putExtra("firstName", "Your First Name Here");
myIntent.putExtra("lastName", "Your Last Name Here");
startActivity(myIntent)
目标类(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");
}
你只需要在表达你的意图时发送额外的信息。
这样地:
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);
使用全局类:
public class GlobalClass extends Application
{
private float vitamin_a;
public float getVitaminA() {
return vitamin_a;
}
public void setVitaminA(float vitamin_a) {
this.vitamin_a = vitamin_a;
}
}
您可以从所有其他类调用该类的setter和getter。要做到这一点,您需要在每个活动中创建一个GlobalClass对象:
GlobalClass gc = (GlobalClass) getApplication();
然后,您可以调用例如:
gc.getVitaminA()