2014-07-07 2 views
1

Android 앱에 SharedPreferences을 처음 사용했습니다. SharedPreferences을 계속해서 사용할 것이므로 SharedPreferencesUtil이라는 유틸리티 클래스를 만들었습니다.이 유틸리티 클래스에는 값에 액세스하고 수정할 수있는 많은 정적 메서드가 포함되어 있습니다. 예를 들어 :SharedPreferencesUtil 만들기

/** 
    * This method is used to add an event that the user 
    * is looking forward to. We use the objectId of a ParseObject 
    * because every object has a unique ID which helps to identify the 
    * event. 
    * @param objectId The id of the ParseObject that represents the event 
    */ 
    public static void addEventId(String objectId){ 
     assert context != null; 
     prefs = context.getSharedPreferences(Fields.SHARED_PREFS_FILE, 0); 
     // Get a reference to the already existing set of objectIds (events) 
     Set<String> myEvents = prefs.getStringSet(Fields.MY_EVENTS, new HashSet<String>()); 
     myEvents.add(objectId); 
     SharedPreferences.Editor editor = prefs.edit(); 
     editor.putStringSet(Fields.MY_EVENTS, myEvents); 
     editor.commit(); 
    } 

나는 질문의 몇 가지가 있습니다
1.이 유틸리티 클래스 SharedPreferencesUtil을 가지고 좋은 결정인가?
2. assert의 사용이 적절합니까?
3. String을 어떻게 추가 할 예정입니까?

답변

1

일반적으로이 유틸리티 클래스는 훌륭하다고 생각합니다. 내가 가지고있는 것 몇 가지 권장 사항은 다음과 같습니다

  1. 은 (Application.onCreate()에서) 응용 프로그램의 하위 클래스에 컨텍스트를 초기화하고 유틸리티 클래스에서 해당에 대한 참조를 저장합니다. Activity 컨텍스트 대신 응용 프로그램 컨텍스트 만 사용하도록하고, SharedPreferences는 테마 특성을 사용하지 않으므로 Activity 컨텍스트를 사용하지 않아도되므로 메모리 누수에 대해 걱정할 필요가 없습니다.

  2. 초기화없이 클래스를 사용하려고 시도하면 클래스가 아직 초기화되지 않았다는 경고를 확인하고 throw하십시오. 이 방법을 사용하면 null 컨텍스트를 확인하는 것에 대해 걱정할 필요가 없습니다. 아래 예를 보여 드리겠습니다. 기본적으로


    public final class Preferences { 
        private static Context sContext; 
    
        private Preferences() { 
         throw new AssertionError("Utility class; do not instantiate."); 
        } 
    
        /** 
        * Used to initialize a context for this utility class. Recommended 
        * use is to initialize this in a subclass of Application in onCreate() 
        * 
        * @param context a context for resolving SharedPreferences; this 
        *    will be weakened to use the Application context 
        */ 
        public static void initialize(Context context) { 
         sContext = context.getApplicationContext(); 
        } 
    
        private static void ensureContext() { 
         if (sContext == null) { 
          throw new IllegalStateException("Must call initialize(Context) before using methods in this class."); 
         } 
        } 
    
        private static SharedPreferences getPreferences() { 
         ensureContext(); 
         return sContext.getSharedPreferences(SHARED_PREFS_FILE, 0); 
        } 
    
        private static SharedPreferences.Editor getEditor() { 
         return getPreferences().edit(); 
        } 
    
        public static void addEventId(String eventId) { 
         final Set<String> events = getPreferences().getStringSet(MY_EVENTS, new HashSet<String>()); 
    
         if (events.add(eventId)) { 
          // Only update the set if it was modified 
          getEditor().putStringSet(MY_EVENTS, events).apply(); 
         } 
        } 
    
        public static Set<String> getEventIds() { 
         return getPreferences().getStringSet(MY_EVENTS, new HashSet<String>()); 
        } 
    } 
    

, 이것은 당신이 항상 된 SharedPreferences를 사용하는 반면에 컨텍스트가 필요 피할 수 있습니다. 대신 응용 프로그램 컨텍스트에 대한 참조가 항상 유지됩니다 (Application.onCreate()에서 초기화해야 함).

+0

포인트 1은 내가 현재하고있는 것입니다. 포인트 2는 내가하고 싶은 일이지만 어설 션은 더 단순 해 보였습니다. –

+1

어설 션은 기본적으로 활성화되어 있지 않으므로 앱을 릴리스 할 때 그대로두면 안됩니다. 게다가 적절한 해결 방법 (call initialize())을 명시하는 특정 예외를 던지는 것이 좋습니다. – kcoppock

1

SharedPreferences를 올바르게 사용하는 방법을 확인하고 here을 확인하고 Android docs에서 다른 예를 확인할 수 있습니다.

편집 : 디자인 질문에 관해서는, 정말 정적 클래스를 가지지 않아도 상관 없습니다. 귀하의 SharedPreferences

이 응용 프로그램을 통해을 공유하고, 여러 SharedPreferences 개체를 만들 수 있지만, 그들은 본질적으로 저장하고 당신은 단지 하나 개의 객체를 사용하는 경우로 응용 프로그램의 동일한 부분에 저장할 수 있습니다.

+0

아! 나는'SharedPrefernces'의 메소드를 사용하는 방법을 안다. 그 정적 방법을 가지고 좋은 디자인 결정인지 알고 싶습니다 –

+0

정말 정적 유틸리티 클래스를 사용하여 차이를 만들지 말아야하는지. – rageandqq