我有一个场景,在通过登录页面登录后,每个活动都会有一个注销按钮。

单击注销时,我将传递要注销的登录用户的会话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对象在活动之间发送数据。假设您有两个活动,即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 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();

//您的问题是,您希望在登录后存储会话id,并将该会话id用于要注销的每个活动。

//问题的解决方案是成功登录后必须将会话id存储在公共变量中。每当您需要注销会话id时,您可以访问该变量并将变量值替换为零。

//Serializable class

public class YourClass  implements Serializable {
     public long session_id = 0;
}

您可以使用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();

这非常有用,因为一次保存值,然后检索任何活动。

/*
 * 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));
    }
}