show some of the methods to save a state of night on an android phone?

I did the same thing for my application in Kotlin. But you can convert it to java, is almost the same.

You need to create a new class for Sharing Preferences:

class SettingsSaveData(context:Context) {

private var sharedPreferences: SharedPreferences =context.getSharedPreferences("file", Context.MODE_PRIVATE)

fun setDarkMode(state: Boolean){
    val editor = sharedPreferences.edit()
    editor.putBoolean("Dark", state)
    editor.apply()
}

fun loadDarkMode(): Boolean? {
    val state = sharedPreferences.getBoolean("Dark", false)
    return (state)
}

}

In your Settings Activity, you need to have something like this:

class SettingsActivity : AppCompatActivity() {   
   private lateinit var settingSaveData: SettingsSaveData

override fun onCreate(savedInstanceState: Bundle?) {
    settingSaveData = SettingsSaveData(this)  // make sure to setTheme here
    if (settingSaveData.loadDarkMode() == true){  // before onCreate method
        setTheme(R.style.DarkTheme)
    }else{
        setTheme(R.style.AppTheme)
    }

    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_settings)

    if(settingSaveData.loadDarkMode() == true){
        switch_theme.isChecked = true            // switch_theme is my Switch
    }

    switch_theme.setOnCheckedChangeListener { _, isChecked ->
        if (isChecked) {
            settingSaveData.setDarkMode(true)
            restartApplication()
        }else{
            settingSaveData.setDarkMode(false)
            restartApplication()
    }  
private fun restartApplication(){
    val i = Intent(applicationContext, SettingsActivity::class.java)
    startActivity(i)
    finish()
}

In all your activities you just need to declare:

private lateinit var settingsSaveData:SettingsSaveData

and setTheme in your onCreate method:

 settingsSaveData = SettingsSaveData(this)
    if (settingsSaveData.loadDarkMode() == true){
        setTheme(R.style.DarkTheme)
    }else{
        setTheme(R.style.AppTheme)
    }
    super.onCreate(savedInstanceState)

I hope this will help you!

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top