Kotlin Objects loading delay


#1

Hi I have a strange issue, I have an initial Login activity in Android, while onCreateMethod of it, is triggered, where I called by Object class which is a static object named BaseData. I get a strange null error, while its an object. Found that objects are lazy loaded in Kotlin, How do i force it to load first and be available when my main Landing Login Activity is created.

class LoginActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
if(BaseData.userId == “”) { //At this step BaseData itself comes as null, so app goes blank
//Do something
}
}
}

object BaseData : Observable() {
var initialSyncDone:Boolean = false
var isOffline:Boolean = true
var userId: String = “”

init{
// I have logic to load userId from shared prferences
}
}


#2

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”) != null) Preferences.getPref(“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 getPref(key:String) : T?{
val gson = Gson()
val jsonString = pref!!.getString(key,"")
if(jsonString != “”) {
val type = object : TypeToken() {}.type
return gson.fromJson(jsonString, type)
}
else
return null
}