有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用SharedReference的许多用户的java登录

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

我有以下代码

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

我用的是Android Studio


共 (2) 个答案

  1. # 1 楼答案

    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.

  2. # 2 楼答案

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

    如果您使用的是SharedReference,只需区分密钥名,例如:“User1_session_login”、“User2_session_login”

    public void setLoggedIn(String key,boolean loggedin){
                editor.putBoolean(key,loggedin);
                editor.commit();
    }