Android - How to use SharedPreferences in non-Activity class?

后端 未结 12 2325
日久生厌
日久生厌 2020-12-13 08:54

How do you use SharedPreferences in a non-Activity class? I tried making a generic Preferences utility class and importing android.content.Context but Eclipse s

12条回答
  •  失恋的感觉
    2020-12-13 09:13

    use this code to a new class.

    import android.content.Context;
    import android.content.SharedPreferences;
    
    /**
       * Created by Atiar Talukdar on 6/5/2017.
    */
    
    public class TemporaryStorageSharedPreference {
    protected final static int DEFAULT = 0;
    int temp = 0;
    
    public int readSharedPreference(Context context, String spName,String key){
        SharedPreferences sharedPreferences = context.getSharedPreferences(spName, Context.MODE_PRIVATE);
        return temp = sharedPreferences.getInt(key,DEFAULT);
    }
    
    public void writeSharedPreference(Context context,String ammount,String spName,String key ){
    
        SharedPreferences sharedPreferences = context.getSharedPreferences(spName, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt(key, DEFAULT);
        editor.commit();
    }
    }
    

提交回复
热议问题