OGeek|极客世界-中国程序员成长平台

标题: java - 一旦用户登录,我应该使用类实例(序列化)还是 Singleton 来存储 userInfo [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 18:19
标题: java - 一旦用户登录,我应该使用类实例(序列化)还是 Singleton 来存储 userInfo

我想知道在用户登录后存储用户信息的更好方法是什么。我应该将数据解析为 Serizaled 对象类吗?或者我应该创建一个单例。大多数情况下,一旦我登录,我就会从服务器收到大约 12-13 个对象,但是其中 2-3 个在整个应用程序中都被使用,其他的不是很常见。



Best Answer-推荐答案


您有多种选择。在这里阅读:https://developer.android.com/guide/topics/data/data-storage.html

在你的情况下,也许你可以简单地使用 SharedPreferences,这里:https://developer.android.com/guide/topics/data/data-storage.html#pref

    SharedPreferences sharedPreferences = context.getSharedPreferences("FILE_NAME",
            Context.MODE_PRIVATE);

放置值: (如果您关心 putString 是否成功,请使用 .commit() 而不是 .apply())

    SharedPreferences sharedPreferences = context.getSharedPreferences(COOKIE_SP_FILE_NAME,
            Context.MODE_PRIVATE);
    if (sharedPreferences != null) {
        sharedPreferences.edit().putString("KEY", "VALUE").apply();
    }

要检索值:

    SharedPreferences sharedPreferences = context.getSharedPreferences("FILE_NAME", Context.MODE_PRIVATE);
    if (sharedPreferences != null) {
        String theString = sharedPreferences.getString("KEY", "DEFAULT_VALUE");
    }

如果没有找到以“KEY”为键的值,则“DEFAULT_VALUE”是您将获得的值。

关于java - 一旦用户登录,我应该使用类实例(序列化)还是 Singleton 来存储 userInfo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45210161/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4