Git Product home page Git Product logo

Comments (4)

Blankj avatar Blankj commented on May 19, 2024

你这是单例了,这样sp的name不能修改了

from androidutilcode.

ssyijiu avatar ssyijiu commented on May 19, 2024

怎么说呢,代码量大到一定程度后,自己写的也不敢确定sp的name在哪里改了,所以现在这样 我要是用的话在get和put之前肯定会先初始化一下sp的name,但这样又很麻烦,不这样心里不放心。

from androidutilcode.

ssyijiu avatar ssyijiu commented on May 19, 2024

建议这样,大多数用一个单例的sp,有特殊保存比如token还是自己重新封装好:

   // 如果需要一个单独的SharedPreferences来保存某些数据,例如:token,可以这样:
private static final String PRE_TOKEN = "token";
private static SharedPreferences getInstance(Context context, String preferenceName) {
    if(sp == null) {
        sp = context.getSharedPreferences(preferenceName, Context.MODE_PRIVATE);
    }
    return sp;
}

public static void putToken(Context context, String token) {
    sp = getInstance(context,PRE_TOKEN);
    sp.edit().putString(PRE_TOKEN, token).apply();
}

public static String getToken(Context context) {
    sp = getInstance(context,PRE_TOKEN);
    return sp.getString(PRE_TOKEN,"");
}

from androidutilcode.

Blankj avatar Blankj commented on May 19, 2024

保存特殊的只需要改name就好了挺方便的,单例的话就修改不了,还要重新开一个单例,其实单例只是为了复用上次存在的值,而这个单例的区别就是getSharedPreferences这一个步骤,你是直接读取上次的sp,而我是调用getSharedPreferences获得,性能基本没区别啦,考虑到使用方便就不单例了

from androidutilcode.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.