I am working on an Android Studio project where I am using a singleton class to keep track of data (I have already done research on the pros and cons of singleton objects, and I decided it was the best solution for my project). I am, however, running into a few problems that seem to point back to my singleton object, for which I have not been able to find any good solutions on StackOverflow or other developer forums.
- The first error I'm getting happens where I call the singleton object in another class.
Note: I am not instantiating this singleton class before using it, because if I understand Kotlin singletons correctly, you don't have to.
for (item in items) {
with(item.device) {
if (name == "BLE_DEVICE") {
count++
Data.addresses.add(address) >>> This is where I call the singleton object <<<
}
}
}
- The second error I get comes from my initialization of SharedPreferences in the singleton class.
var sharedPref: SharedPreferences? = MainActivity().getSharedPreferences("MySharedPreferencesFile", Context.MODE_PRIVATE)
- The third error I get comes from calling this function from my singleton object.
fun saveSharedPreferences() {
for ((key, value) in names) {
if (sharedPref != null) {
if (!sharedPref?.contains(key)!!) {
sharedPref
?.edit()
?.putString(key, value)
?.apply()
}
}
}
}
FOR REFERENCE:
a. Here are the important lines from my stack trace...
2022-08-30 16:07:05.422 9946-9946/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.punchthrough.blestarterappandroid, PID: 9946
>>> java.lang.ExceptionInInitializerError
>>> at com.punchthrough.blestarterappandroid.ScanResultAdapter.getItemCount(ScanResultAdapter.kt:62)
...
...
>>> Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
>>> at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:174)
>>> at com.punchthrough.blestarterappandroid.Data.<clinit>(Data.kt:35)
at com.punchthrough.blestarterappandroid.ScanResultAdapter.getItemCount(ScanResultAdapter.kt:62)
b. This is my singleton class used for tracking data.
object Data {
// Format: <Device Address, Name>
// Used for keeping a record of all the devices, keeping
// duplicate advertisements off the screen, and saving the
// user-inputted names to the MAC address
var names: MutableMap<String, String> = mutableMapOf()
// Format: <Device Address>
// Used for keeping a count of how many views should be populated
// in the RecyclerView
var addresses = mutableSetOf<String>()
// TODO: Fix this line to resolve an initialization error
var sharedPref: SharedPreferences? = MainActivity().getSharedPreferences("MySharedPreferencesFile", Context.MODE_PRIVATE)
fun saveSharedPreferences() {
for ((key, value) in names) {
if (sharedPref != null) {
if (!sharedPref?.contains(key)!!) {
sharedPref
?.edit()
?.putString(key, value)
?.apply()
}
}
}
}
}