Skip to content

Instantly share code, notes, and snippets.

@rafsanjani
Last active January 29, 2020 10:47
Show Gist options
  • Save rafsanjani/f4cd057b1407843fae3ef21ccacdfa98 to your computer and use it in GitHub Desktop.
Save rafsanjani/f4cd057b1407843fae3ef21ccacdfa98 to your computer and use it in GitHub Desktop.
Shared Preference with type safety
package com.example.application.util
// Created by Rafsanjani on 01/24/2020.
import android.content.Context
class SharedPrefs(context: Context) {
companion object {
//declare all constants here for things you would like to persist
private const val IS_FIRST_TIME_LAUNCH = "com.example.application.is_first_time_launch"
}
//this will be the name of the xml file which will contain the key-value pairs of the preferences
//we want to make this unique to our application. we can use context.packageName as well
private val fileName = "com.example.application.shared_prefs"
private val settings: SharedPreferences = context.getSharedPreferences(fileName, Context.MODE_PRIVATE)
private val editor = settings.edit()
/**
* Store a value which tells the context that the application is starting for the first time. This is
* for performing operations that are only necessary when the application is running for the first time
*
*/
var firstTimeLaunch: Boolean
get() = settings.getBoolean(IS_FIRST_TIME_LAUNCH, true)
set(isFirstTime) = editor.putBoolean(IS_FIRST_TIME_LAUNCH, isFirstTime).apply()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment