Rahul Biswas
Rahul Biswas

Reputation: 79

Android data lost on theme change (Light/Dark mode)

Android: I have made a simple Todo list app using Kotlin. And the theme (Light/Dark) of this app is set to system default theme MODE_NIGHT_FOLLOW_SYSTEM. Now the problem is that when I changed theme to Dark mode(because my emulator's theme was set to Light theme previously), all added Todo items were gone and same when I changed to Light mode again. Then I noticed the size of my ArrayList became 0 (empty).

Here is screenshots to understand it better:

Light Mode

https://i.sstatic.net/eWbzO.png

after changing system theme to Dark

Dark Mode

https://i.sstatic.net/B9iqg.png

tasks are added to list: ArrayList when saveButton: Textview is clicked

class MainActivity : AppCompatActivity() {
    var modified = false
    private lateinit var listView: ListView
    private lateinit var input: EditText
    private lateinit var saveButton: TextView
    private lateinit var cancelButton: TextView

    private val list = ArrayList<String>()
    private lateinit var listAdapter: CustomAdapter
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        listView = findViewById(R.id.listView)
        input = findViewById(R.id.input)
        saveButton = findViewById(R.id.saveBtn)
        cancelButton = findViewById(R.id.cancelBtn)

        listAdapter = CustomAdapter(this, list)
        listView.adapter = listAdapter

        val warningToast = Toast.makeText(this,
            "The text may be empty or contains only spaces",
            Toast.LENGTH_LONG)

        saveButton.setOnClickListener {
            val text = input.text.toString()
            // if text is empty or only contains blank
            if (text.isEmpty() || text.isBlank()) {
                warningToast.show()
                return@setOnClickListener
            }
            if (!modified) {
                // output list size 0 after changing theme 
                Log.d("MY_DEBUG", "size fo list is : ${list.size}")
                list.add(input.text.toString())
            } else {
                // ...
            }
            input.text.clear()
            listAdapter.notifyDataSetChanged()
        }
       
        // ...

    }
}

I thought that this is because it triggers a uiMode configuration change when theme mode is changed. So, the activity is recreated automatically. I want to keep added items even after changing theme. Is there any way to prevent loss of added items. Thank you!

Upvotes: 0

Views: 1351

Answers (1)

Sepehr1812
Sepehr1812

Reputation: 91

Changing theme recreates your activity and it reinitiates your list. It is not because of changing theme itself.

You have to save your data persistently, in a database or in a SharedPreferences instance with your own serialization method (like JSON).

Upvotes: 0

Related Questions