Skip to content

Instantly share code, notes, and snippets.

@KryptKode
Last active August 12, 2022 17:14
Show Gist options
  • Save KryptKode/658a0e96f7b3895e341ce25bfb6baeb9 to your computer and use it in GitHub Desktop.
Save KryptKode/658a0e96f7b3895e341ce25bfb6baeb9 to your computer and use it in GitHub Desktop.
Different Shared Prefs
import android.content.SharedPreferences
import android.net.Credentials
class CredentialsPreferences @Inject constructor(
@SharedPref(SharedPrefsType.Credentials)
private val sharedPreferences: SharedPreferences,
) {
fun getCredentials(): Credentials {
return sharedPreferences.getString(CRED_KEY, "").toCredentials()
}
fun setCredentials(credentials: Credentials) {
sharedPreferences.edit().putString(CRED_KEY, credentials.toString()).apply()
}
companion object {
private const val CRED_KEY = "cred_key"
}
}
import android.content.SharedPreferences
class LoginPreferences @Inject constructor(
@SharedPref(SharedPrefsType.Login)
private val sharedPreferences: SharedPreferences,
) {
fun isLoggedIn(): Boolean {
return sharedPreferences.getBoolean(LOGGED_IN_KEY, false)
}
fun setLoggedIn(): Boolean {
sharedPreferences.edit().putBoolean(LOGGED_IN_KEY, true).apply()
}
private companion object {
const val LOGGED_IN_KEY = "log_in"
}
}
import android.content.Context
import android.content.SharedPreferences
@Module
class PrefsModule {
@Provides
@SharedPref(SharedPrefsType.Credentials)
fun provideCredentialsPreferences(context: Context): SharedPreferences{
return EncryptedSharedPreferences.create(
"credentails_prefs",
context,
)
}
@Provides
@SharedPref(SharedPrefsType.Login)
fun provideLoginPreferences(context: Context): SharedPreferences{
return EncryptedSharedPreferences.create(
"login_prefs",
context,
)
}
}
// prefer using custom qualifier annotation with enum over @Named because it's easier to maintain
// https://bloggie.io/@_junrong/dagger-2-for-android-part-iii-the-qualifier-and-named-annotation#tweaking-%40namedclone-to-use-enum
@Qualifier
@MustBeDocumented
@Retention(AnnotationRetention.RUNTIME)
annotation class SharedPref(val color: SharedPrefsType) {
}
enum class SharedPrefsType {
Credentials, Login
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment