I had things resolved with the code. I was not able to debug nor get error, just a plain black screen, so I had an assumption of Objects are lazy loaded, but actually not. Also init function in the Object was happening,
But crash was happening at SharePreferences retrieval from json back to Kotlin Object, but no error thrown and black screen on simulator was the confusion. May be better debugging support in Android Studio may help here and scope of improvement needed.
So I went random through evaluate expressions, to identify issue was at getPref method and atlast adding instead of helped, still yet to study what reified means, will do that shortly.
But closing the issue as resolved after these changes in the code done as follows :
class LoginActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
BaseData.loadPrefData()
if(BaseData.userId == “”) {
//Do something
}
}
}
object BaseData : Observable() {
var initialSyncDone:Boolean = false
var isOffline:Boolean = true
var userId: String = “”
fun loadPrefData // init works but debugging was not happening so no errors before
{
if(Preferences.pref!!.contains("user")) {
userId = if(Preferences.getPref<User>("user") != null) Preferences.getPref<User>("user")!!.id!! else ""
}
}
// Preference class get from SharePreferences
// **reified** was the missing one, i didn't had before, so it was
// crashing to convert from Preferences back to Kotlin Object, but no debug errors.
inline fun <reified T> getPref(key:String) : T?{
val gson = Gson()
val jsonString = pref!!.getString(key,"")
if(jsonString != "") {
val type = object : TypeToken<T>() {}.type
return gson.fromJson<T>(jsonString, type)
}
else
return null
}
//At this step BaseData itself comes as null, so app goes blank— if BaseData was null,BaseData.userIdwould be causing NullPointerException. Kotlin's lazy object loading is based on JVM class loading — you won't notice this lazyness at all. - Miha_x64