App_SharedPrefs Pattern - jorgepascoPE/Kotlin-snippets GitHub Wiki
The App/SharedPreference is an Android pattern for handling and persisting data in an application. It's particularly useful for apps that require login or persistent objects, like messages or channels.
This methodology uses a nested application to store the data. In this page we are going to overview the process to setup a Chat application to work with this pattern.
SharedPrefs
import android.content.Context
import android.content.SharedPreferences
import com.android.volley.toolbox.Volley
class SharedPrefs (context: Context){
private val PREFS_FILE_NAME = "prefs"
private val prefs: SharedPreferences = context.getSharedPreferences(PREFS_FILE_NAME, mode) //mode 0 means content private
private val IS_LOGGED_IN = "isLoggedIn"
private val AUTH_TOKEN = "authToken" // The backend application requires an authToken to execute certain calls like getting chat channels and messages.
private val USER_EMAIL = "userEmail"
var isLoggedIn: Boolean //custom getters and setters
get() = prefs.getBoolean(IS_LOGGED_IN, false) //default value: false
set(value) = prefs.edit().putBoolean(IS_LOGGED_IN, value).apply()
var authToken: String
get() = prefs.getString(AUTH_TOKEN, "")
set(value) = prefs.edit().putString(AUTH_TOKEN, value).apply()
var userEmail: String
get() = prefs.getString(USER_EMAIL, "")
set(value) = prefs.edit().putString(USER_EMAIL, value).apply()
// Every Volley request of the application is going to be handled from here
val requestQueue = Volley.newRequestQueue(context)
}
App class
import android.app.Application
import app-package.Utilities.SharedPrefs
class App : Application() {
//Like a Singleton but inside a specific class
companion object {
lateinit var prefs: SharedPrefs
}
override fun onCreate() {
prefs = SharedPrefs(applicationContext)
super.onCreate()
}
}
Android Manifest
You should reference the new App class in your android:name
attribute, inside the opening application tag of the Android Manifest, as follows:
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:name=".Controller.App">
UserDataService object
import app-package.Controller.App
object UserDataService {
var id = ""
var email = ""
var name = ""
fun logout() {
id=""
email =""
name =""
App.prefs.authToken = ""
App.prefs.userEmail = ""
App.prefs.isLoggedIn = false
MessageService.clearMessages()
MessageService.clearChannels()
}
}