1

如何创建具有共享首选项的多会话,以便两个用户可以在同一个会话中登录和注销?

我有以下代码。

public class Session 
{
    SharedPreferences prefs;
    SharedPreferences.Editor editor;
    Context ctx;
    String [][] usuarios;
    int i,j;

    public Session(Context ctx)
    {
        this.ctx = ctx;
        prefs = ctx.getSharedPreferences("init", Context.MODE_PRIVATE);
        editor = prefs.edit();
    }

    public void setLoggedIn(boolean loggedin)
    {
        editor.putBoolean("loggedinmode",loggedin);
        editor.commit();
    }

    public boolean loggedin()
    {
        return prefs.getBoolean("loggedinmode",false);
    }
}

我正在使用安卓工作室。

4

2 回答 2

0

You can store lists, you just have to use a clever way. There is this library called Gson it can be serialize and deserialize java objects. So what you can do is create a list of objects call Gson.toJson which converts the object into json string representation of that object, then take it and store as String in shared preference with your unique name.Then to modify read from it, use fromJson , do your thing and save. Hint, this operation can be taxing though it works, consider in the long run to use databases, realm is great.

于 2017-04-18T02:04:38.947 回答
0

为什么不使用 SQLite?Sharedpreferences 也可以,但 sharedpreferences 旨在保存简单值。

如果您使用 SharedPreferences,只需区分键名 ex:“User1_session_login”、“User2_session_login”

public void setLoggedIn(String key,boolean loggedin){
            editor.putBoolean(key,loggedin);
            editor.commit();
}
于 2017-04-18T02:15:49.263 回答