2017-12-15 3 views
1

kotlin을 사용하여 안드로이드에 SharedPreference의 도우미 클래스를 만들고 싶습니다. 불행히도 Context이 필요하며 매번 통화를 선호하는 매개 변수로 설정하고 싶지 않습니다.안드로이드 - SharedPreferences - 컨텍스트

내가 컨텍스트에 대한 동반자 객체를 사용하고 난 다음 오류 얻을 응용 프로그램 시작시 설정하면 :

Do not place Android context classes in static fields; this is a memory leak (and also breaks Instant Run) 그래서 어떻게 매번 내가 환경 설정을 호출 거치지 않고 컨텍스트를 얻을 수 있습니까?

var isWorking: Boolean 
    get() = getBoolean(IS_WORKING) 
    set(isWorking) = setPreference(IS_WORKING, isWorking) 

private fun setPreference(key: String, value: Boolean) { 
    val editor = settings.edit() 
    editor.putBoolean(key, value) 
    editor.commit() 
} 

private val settings: SharedPreferences by lazy { 
    context.getSharedPreferences("prefs", Context.MODE_PRIVATE) 
} 
+1

이 질문에 대한 대답은 아니지만 매번 컨텍스트를 전달해야합니다. 메시지가 말하기를, 활동이 끝났을 때 작업이 여전히 실행 중이면 활동이 누수 될 수 있습니다. 내 경험에 비추어 볼 때, 어떤 작업이있을 때 컨텍스트를받는 PreferenceHelper 클래스를 항상 보았습니다. –

답변

5

당신은 extension function 아래와 같이 만들 수 있습니다

object PreferenceHelper { 

    fun defaultPrefs(context: Context): SharedPreferences 
      = PreferenceManager.getDefaultSharedPreferences(context) 

    fun customPrefs(context: Context, name: String): SharedPreferences 
      = context.getSharedPreferences(name, Context.MODE_PRIVATE) 

    inline fun SharedPreferences.edit(operation: (SharedPreferences.Editor) -> Unit) { 
      val editor = this.edit() 
      operation(editor) 
      editor.apply() 
     } 
} 

편집 : Here이 응답에 대한 참조입니다. 리팩토링하는 방법을 확인하려면 util classesKotlin 트릭으로 사용하고 사용하십시오.

Edit2가이 :

당신은 클래스에 도우미를 변경하고 Application이 init을 할 수 있습니다. 그렇다면 어디에서나 사용할 수 있습니다. 나는 이것이 당신이하려는 일이라고 생각합니다. 해보자.

YourApp.prefHelper.defaultPrefs().edit { 
    // Your shared pref operations. 
} 

내가 처음이 가장 좋은 방법이지만 더 가까운 생각 : 아래처럼 원하는 목적지

class YourApp : Application() { 

    override fun onCreate() { 
     super.onCreate() 
     YourApp.prefHelper = PreferenceHelper(this) 
    } 

    companion object { 
     lateinit var prefHelper: PreferenceHelper 
      private set 
    } 
} 

그리고 당신은 사용할 수 있습니다

class PreferenceHelper constructor(context: Context){ 

     fun defaultPrefs(): SharedPreferences 
       = PreferenceManager.getDefaultSharedPreferences(context) 

     fun customPrefs(name: String): SharedPreferences 
       = context.getSharedPreferences(name, Context.MODE_PRIVATE) 

     inline fun SharedPreferences.edit(operation: (SharedPreferences.Editor) -> Unit) { 
       val editor = this.edit() 
       operation(editor) 
       editor.apply() 
      } 
    } 

그리고 당신의 응용 프로그램 클래스

두 번째 것도 괜찮습니다. 필요한 것을 사용할 수 있습니다. 또한 위에 제공된 링크 내용에 더 멋진 예제가 있습니다.

+0

답변 해 주셔서 감사합니다. 하지만 그건 내가 원한 것이 아닙니다. 생성자를 사용하여 헬퍼 클래스를 호출 할 때 차이점은 없습니다. –

+1

나는 나의 대답을 편집하고 당신이하고 싶은 것을 실행하려고 노력했다. 나는 첫 번째 것을 선호하지만 두 번째 것은 okey입니다. – savepopulation

0

내 문제에 대한 해결책을 찾았습니다. 나는 문맥 대신에 변수 SharedPreferences을 지속시킴으로써 그것을 해결했다.

object PreferenceDao { 
    private lateinit var settings: SharedPreferences 

    fun init(context: Context) { 
     settings = context.getSharedPreferences("prefs", Context.MODE_PRIVATE) 
    } 
} 

init 함수가 내 Application 클래스에서 호출됩니다.

+0

의존성 주입 프레임 워크 사용을 고려 했습니까? – tynn

+0

그게 뭐죠? 그것을 결코 들어 보지 못했다. –

관련 문제