我有一个场景,在通过登录页面登录后,每个活动都会有一个注销按钮。
单击注销时,我将传递要注销的登录用户的会话id。有人能指导我如何让所有活动都可以使用会话id吗?
本案的任何替代方案
我有一个场景,在通过登录页面登录后,每个活动都会有一个注销按钮。
单击注销时,我将传递要注销的登录用户的会话id。有人能指导我如何让所有活动都可以使用会话id吗?
本案的任何替代方案
当前回答
您可以使用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”)等。
其他回答
你只需要在表达你的意图时发送额外的信息。
这样地:
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 MyActivity extends Activity {
public static String SharedString;
public static SomeObject SharedObject;
//...
我在类中使用静态字段,并获取/设置它们:
喜欢:
public class Info
{
public static int ID = 0;
public static String NAME = "TEST";
}
要获取值,请在“活动”中使用:
Info.ID
Info.NAME
要设置值:
Info.ID = 5;
Info.NAME = "USER!";
您可以使用Intent
Intent mIntent = new Intent(FirstActivity.this, SecondActivity.class);
mIntent.putExtra("data", data);
startActivity(mIntent);
另一种方法可以是使用单例模式:
public class DataHolder {
private static DataHolder dataHolder;
private List<Model> dataList;
public void setDataList(List<Model>dataList) {
this.dataList = dataList;
}
public List<Model> getDataList() {
return dataList;
}
public synchronized static DataHolder getInstance() {
if (dataHolder == null) {
dataHolder = new DataHolder();
}
return dataHolder;
}
}
从您的第一次活动
private List<Model> dataList = new ArrayList<>();
DataHolder.getInstance().setDataList(dataList);
关于第二项活动
private List<Model> dataList = DataHolder.getInstance().getDataList();
您可以使用SharedPreferences。。。
登录中。SharedPreferences中的时间存储会话idSharedPreferences preferences=getSharedPreferences(“会话”,getApplicationContext().MODE_PRIVATE);编辑器编辑器=preferences.edit();editer.putString(“sessionId”,sessionId);editer.commit();注销。共享引用中的时间提取会话idSharedPreferences preferences=getSharedPreferences(“会话”,getApplicationContext().MODE_PRIVATE);String sessionId=首选项.getString(“sessionId”,null);
如果您没有所需的会话id,请删除sharedpreferences:
SharedPreferences settings = context.getSharedPreferences("session", Context.MODE_PRIVATE);
settings.edit().clear().commit();
这非常有用,因为一次保存值,然后检索任何活动。