Search code examples
androidkotlinsharedpreferences

Any idea why Android Kotlin SharedPreferences is crashing my app?


I try to save a key-value pair persistently by use of shared preferences in Android Kotlin. When putting the object initialisation into my mainActivity-Class and run it in debug mode on my phone the app immediately crashes with no debug information.

Phone: Samsung SM-A146P OS: Android 15 / UI Core 5.1

The following code is causing the crash:

class MainActivity : AppCompatActivity() {

val sharedPreferences = this.getSharedPreferences("com.xpz.prefs", Context.MODE_PRIVATE)
 ... }

I have no clue why it is not working. Do I need to set some permission?


Solution

  • you initialize SharedPreferences in the MainActivity, before the Activity has been fully constructed. you should place it in the onCreate

    class MainActivity : AppCompatActivity() {
    
        private lateinit var sharedPreferences: SharedPreferences
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            sharedPreferences = this.getSharedPreferences("com.xpz.prefs", Context.MODE_PRIVATE)
    
        }
    }