2016-03-10 12 views
7

Sto facendo una classe helper SharedPreferences per rendere il mio codice un aspetto gradevole.Classe helper SharedPreferences

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(); 
    } 
} 

La domanda è: Devo fare questi metodi statici e inizializzare SharedPreferences in ogni metodo o meglio a sinistra non statica e chiamare classe SharedPreferencesHelper una volta dalle mie altre classi? Grazie

+0

Fa qualcosa di diverso se lo fai statico o no? –

risposta

3

Non terrei un riferimento al contesto. Preferirei mantenere il SharedPreference e il suo Editor come membro statico della classe helper. In questo modo non è necessario istanziare SharedPreferencesHelper ogni volta che è necessario leggere/scrivere SharedPreference. Un ulteriore passo avanti è l'applicazione Context (con una sottoclasse dell'applicazione personalizzata) per inizializzare sia SharedPreference sia Editor, la prima volta che si accede all'helper stesso. Ecco come lo modifico

+0

per favore potresti mostrarmi il codice? –

+0

utilizzando dagger2 e avere singleton potrebbe aiutare. e puoi inserire le preferenze di condivisione ovunque vuoi – Raghunandan

+0

@Raghunandan grazie per il suggerimento. Non ho mai usato Dagger, quindi sono un po 'cieco lì. Riguardo al singleton, non vedo la necessità. Alla fine op vuole esporre i metodi per scrivere in read dal sharedpreference – Blackbelt

1

Vorrei usare la classe statica se Context era un contesto "globale" e ottenere valori dal contesto era terribilmente lungo e (un po ') malvagio. In questo modo, ottenere il valore dalla classe statica sarà più semplice senza dover fare l'errore ripetendo ripetutamente la stessa operazione su tutto lo spazio del codice senza commettere errori.

E per quanto riguarda trasformare il vostro, un buon approccio SharedPreferencesHelper statica:

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

Ecco questa classe è che si aiuta.

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(); 
    } 
} 

È possibile ottenere un valore come questo.

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

e memorizzare dati come non

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

Spero il suo aiuto si :)

+0

Sì, non ci saranno dubbi, ma sto cercando di rendere il mio codice semplice. Comunque grazie –

2

Utilizzare questa:

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

Cosa c'è che non va ?? – MrZ

0

ho finito con pattern Singleton, mantenendo una sola istanza al momento:

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(); 
    } 
} 

Nota lo stesso singleton può essere facilmente ottenuto utilizzando la libreria Dagger.