菜鸟教程小白 发表于 2022-12-11 18:19:20

java - 一旦用户登录,我应该使用类实例(序列化)还是 Singleton 来存储 userInfo


                                            <p><p>我想知道在用户登录后存储用户信息的更好方法是什么。我应该将数据解析为 Serizaled 对象类吗?或者我应该创建一个单例。大多数情况下,一旦我登录,我就会从服务器收到大约 12-13 个对象,但是其中 2-3 个在整个应用程序中都被使用,其他的不是很常见。</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>您有多种选择。在这里阅读:<a href="https://developer.android.com/guide/topics/data/data-storage.html" rel="noreferrer noopener nofollow">https://developer.android.com/guide/topics/data/data-storage.html</a> </p>

<p>在你的情况下,也许你可以简单地使用 SharedPreferences,这里:<a href="https://developer.android.com/guide/topics/data/data-storage.html#pref" rel="noreferrer noopener nofollow">https://developer.android.com/guide/topics/data/data-storage.html#pref</a> </p>

<pre><code>    SharedPreferences sharedPreferences = context.getSharedPreferences(&#34;FILE_NAME&#34;,
            Context.MODE_PRIVATE);
</code></pre>

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

<pre><code>    SharedPreferences sharedPreferences = context.getSharedPreferences(COOKIE_SP_FILE_NAME,
            Context.MODE_PRIVATE);
    if (sharedPreferences != null) {
      sharedPreferences.edit().putString(&#34;KEY&#34;, &#34;VALUE&#34;).apply();
    }
</code></pre>

<p>要检索值:</p>

<pre><code>    SharedPreferences sharedPreferences = context.getSharedPreferences(&#34;FILE_NAME&#34;, Context.MODE_PRIVATE);
    if (sharedPreferences != null) {
      String theString = sharedPreferences.getString(&#34;KEY&#34;, &#34;DEFAULT_VALUE&#34;);
    }
</code></pre>

<p>如果没有找到以“KEY”为键的值,则“DEFAULT_VALUE”是您将获得的值。</p></p>
                                   
                                                <p style="font-size: 20px;">关于java - 一旦用户登录,我应该使用类实例(序列化)还是 Singleton 来存储 userInfo,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/45210161/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/45210161/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: java - 一旦用户登录,我应该使用类实例(序列化)还是 Singleton 来存储 userInfo