Is there a way that if information in an EditText is blank, SharedPreferences wont accept it and thus keeping the original data stored?


package com.example.testapp

import android.os.Bundle
import android.view.View
import android.widget.Toast

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {


        bt_button.setOnClickListener {

    private fun saveData() {
        val usernameText = et_username.text.toString()
        tv_username.text = usernameText

        val ipText = et_ipaddress.text.toString()
        tv_ipaddress.text = ipText

        val sharedPreferences = getSharedPreferences("sharedPrefs", MODE_PRIVATE)
        val editor = sharedPreferences.edit()
        editor.apply {
            putString("USERNAME_KEY", usernameText)
            putString("IP_KEY", ipText)
            putBoolean("SWITCH1_KEY", switch1.isChecked)

        Toast.makeText(this,"Data saved! :)", Toast.LENGTH_SHORT).show()

    private fun loadData() {
        val sharedPreferences = getSharedPreferences("sharedPrefs", MODE_PRIVATE)
        val savedUsername = sharedPreferences.getString("USERNAME_KEY", null)
        val savedIp = sharedPreferences.getString("IP_KEY", null)
        val savedBoolean = sharedPreferences.getBoolean("SWITCH1_KEY", false)

        tv_username.text = savedUsername
        tv_ipaddress.text = savedIp
        switch1.isChecked = savedBoolean

This is the code I am using now in my MainActivity.kt.
I want to know if there is a way that if I am entering data in the username field but keeping the ip address field blank/empty, apon clicking the save button (which will put the inputted text into the corresponding textview) if the textviews have data already in them, it wont overwrite both and only the one with the data; in theory then being able to individual save them.


Just use this?

    editor.apply {
        putString("USERNAME_KEY", usernameText)
        if (ipText.isNotEmpty()) putString("IP_KEY", ipText)
        putBoolean("SWITCH1_KEY", switch1.isChecked)

also when setting the text:

   if (ipText.isNotEmpty()) tv_ipaddress.text = ipText

Answered By – Ivo

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published