2016-03-10 13 views
7

Robię klasy pomocniczej SharedPreferences, aby mój kod wyglądał ładnie.SharedPreferences klasa pomocnika

public class SharedPreferencesHelper { 
    Context context; 

    public SharedPreferencesHelper(Context context){ 
     this.context = context; 
    } 

    public boolean isLogged(String prefs){ 
     return context.getSharedPreferences(prefs,Context.MODE_PRIVATE) 
         .getBoolean("LOGGED",false); 
    } 

    public void setLogged(String prefs){ 
     context.getSharedPreferences(prefs,Context.MODE_PRIVATE) 
       .edit().putBoolean("LOGGED",true).apply(); 
    } 
} 

Pytanie powinno uczynić te metody statyczne i zainicjować SharedPreferences w każdej metodzie lub lepiej w lewo to nie statyczne i nazywają klasę SharedPreferencesHelper raz od moich innych klas? Dzięki

+0

Czy to robi różnicę, jeśli sprawisz, że będzie statyczna, czy nie? –

Odpowiedz

3

Nie będę utrzymywać odniesienia do kontekstu. Wolałbym zachować SharedPreference i jego Editor jako statyczny element twojej klasy pomocnika. W ten sposób nie będzie konieczne tworzenie instancji SharedPreferencesHelper za każdym razem, gdy trzeba odczytać/zapisać SharedPreference. Jeden krok dalej użyłby aplikacji Context (z twoją niestandardową podklasą aplikacji), aby zainicjować zarówno SharedPreference, jak i Editor, przy pierwszym dostępie do samego helpera. Tak bym to ukształtował

+0

proszę mi pokazać kod? –

+0

przy użyciu sztyletu 2 i singleton pomoże. i możesz wstrzykiwać preferencje udziału gdziekolwiek chcesz – Raghunandan

+0

@Raghunandan dzięki za podpowiedź. Nigdy nie używałem Sztyletu, więc jestem trochę ślepy. O singletonie, nie widzę potrzeby. Na końcu op chce ujawnić metody pisania w odczycie z sharedpreference – Blackbelt

1

Używałbym klasy statycznej, gdyby Context był kontekstem "globalnym", a uzyskiwanie wartości z kontekstu było gruźlicznie długie i (rodzaj) zło. W ten sposób uzyskanie wartości z klasy statycznej będzie łatwiejsze bez konieczności popełniania błędu powtarzając tę ​​samą operację w całym obszarze kodu bez popełnienia błędu.

A co do toczenia swój SharedPreferencesHelper statyczny, dobre podejście:

public class SharedPreferencesHelper { 

    private SharedPreferencesHelper(Context context){ 
    } 

    private static void ensureNotNull(Context context) { 
     if (context == null) { 
      throw new IllegalArgumentException("Context is null."); 
     } 
    } 

    public static boolean isLogged(Context context, String prefs){ 
     ensureNotNull(context); 
     return context.getSharedPreferences(prefs,Context.MODE_PRIVATE) 
         .getBoolean("LOGGED",false); 
    } 

    public static void setLogged(Context context, String prefs){ 
     ensureNotNull(context); 
     context.getSharedPreferences(prefs,Context.MODE_PRIVATE) 
       .edit().putBoolean("LOGGED",true).apply(); 
    } 
} 
-1

Tutaj ta klasa jest pomóc.

import android.content.Context; 
import android.content.SharedPreferences; 
import android.content.SharedPreferences.Editor; 
import android.preference.PreferenceManager; 
//import android.preference.PreferenceManager; 

public class SharedPreference { 

    private static SharedPreference sharedPreference; 
    public static final String PREFS_NAME = "AOP_PREFS"; 
    public static final String PREFS_KEY = "AOP_PREFS_String"; 



    public static SharedPreference getInstance() 
    { 
     if (sharedPreference == null) 
     { 
      sharedPreference = new SharedPreference(); 
     } 
     return sharedPreference; 
    } 

    public SharedPreference() { 
     super(); 
    } 

    public void save(Context context, String text , String Key) { 
     SharedPreferences settings; 
     Editor editor; 

     //settings = PreferenceManager.getDefaultSharedPreferences(context); 
     settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); //1 
     editor = settings.edit(); //2 

     editor.putString(Key, text); //3 

     editor.commit(); //4 
    } 

    public String getValue(Context context , String Key) { 
     SharedPreferences settings; 
     String text = ""; 
     // settings = PreferenceManager.getDefaultSharedPreferences(context); 
     settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); 
     text = settings.getString(Key, ""); 
     return text; 
    } 

    public void clearSharedPreference(Context context) { 
     SharedPreferences settings; 
     Editor editor; 

     //settings = PreferenceManager.getDefaultSharedPreferences(context); 
     settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); 
     editor = settings.edit(); 

     editor.clear(); 
     editor.commit(); 
    } 

    public void removeValue(Context context , String value) { 
     SharedPreferences settings; 
     Editor editor; 

     settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); 
     editor = settings.edit(); 

     editor.remove(value); 
     editor.commit(); 
    } 
} 

Możesz otrzymać taką wartość.

String KeeLogin = SharedPreference.getInstance().getValue(getApplicationContext(), "YOUR_KEY"); 

i przechowywać dane, takie jak ten

SharedPreference.getInstance().save(LoginScreen.this,"VALUE","YOUR_KEY"); 

Nadzieja jego pomocą :)

+0

Tak, to nie będzie żadnych wątpliwości, ale staram się, aby mój kod wyglądał na prosty. W każdym razie dzięki –

2

Użyj tego:

public class SharedPreferencesHelper { 

public static final String FILE_NAME = "APP_PREFERENCES"; 

    public static void put(Context context, String key, Object object) { 

    SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE); 
    SharedPreferences.Editor editor = sp.edit(); 
    if (object instanceof String) { 
     editor.putString(key, (String) object); 
    } else if (object instanceof Integer) { 
     editor.putInt(key, (Integer) object); 
    } else if (object instanceof Boolean) { 
     editor.putBoolean(key, (Boolean) object); 
    } else if (object instanceof Float) { 
     editor.putFloat(key, (Float) object); 
    } else if (object instanceof Long) { 
     editor.putLong(key, (Long) object); 
    } else { 
     editor.putString(key, object.toString()); 
    } 
    SharedPreferencesCompat.apply(editor); 
} 

    public static Object get(Context context, String key, Object defaultObject) { 

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

    if (defaultObject instanceof String) { 
     return sp.getString(key, (String) defaultObject); 
    } else if (defaultObject instanceof Integer) { 
     return sp.getInt(key, (Integer) defaultObject); 
    } else if (defaultObject instanceof Boolean) { 
     return sp.getBoolean(key, (Boolean) defaultObject); 
    } else if (defaultObject instanceof Float) { 
     return sp.getFloat(key, (Float) defaultObject); 
    } else if (defaultObject instanceof Long) { 
     return sp.getLong(key, (Long) defaultObject); 
    } 

    return null; 
} 

public static void remove(Context context, String key) { 
    SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE); 
    SharedPreferences.Editor editor = sp.edit(); 
    editor.remove(key); 
    SharedPreferencesCompat.apply(editor); 
} 

public static void clear(Context context) { 
    SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE); 
    SharedPreferences.Editor editor = sp.edit(); 
    editor.clear(); 
    SharedPreferencesCompat.apply(editor); 
} 

public static boolean contains(Context context, String key) { 
    SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE); 
    return sp.contains(key); 
} 

public static Map<String, ?> getAll(Context context) { 
    SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE); 
    return sp.getAll(); 
} 



private static class SharedPreferencesCompat { 
    private static final Method sApplyMethod = findApplyMethod(); 

    @SuppressWarnings({"unchecked", "rawtypes"}) 
    private static Method findApplyMethod() { 
     try { 
      Class clz = SharedPreferences.Editor.class; 
      return clz.getMethod("apply"); 
     } catch (NoSuchMethodException e) { 
      e.printStackTrace(); 
     } 

     return null; 
    } 

    public static void apply(SharedPreferences.Editor editor) { 
     try { 
      if (sApplyMethod != null) { 
       sApplyMethod.invoke(editor); 
       return; 
      } 
     } catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException e) { 
      e.printStackTrace(); 
     } 
     editor.commit(); 


    } 
} 
} 
+0

Co jest nie tak? – MrZ

0

skończyło się z Singleton, mając tylko jedną instancję w tym czasie:

import android.content.Context; 
import android.support.annotation.NonNull; 

public class SharedPrefsUtil { 
    private static SharedPrefsUtil instance; 
    private static final String PREFS_NAME = "default_preferences"; 

    public synchronized static SharedPrefsUtil getInstance() { 
     if (instance == null) { 
      instance = new SharedPrefsUtil(); 
     } 
     return instance; 
    } 

    private SharedPrefsUtil() { 
    } 

    public boolean isLoggedIn(@NonNull Context context) { 
     return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) 
       .getBoolean("LOGGED", false); 
    } 

    public void setLoggedIn(@NonNull Context context, boolean value) { 
     context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) 
       .edit().putBoolean("LOGGED", value).apply(); 
    } 
} 

Uwaga ten sam singleton można łatwo uzyskać przy użyciu biblioteki Dagger.

Powiązane problemy