Search code examples
androidkotlinsharedpreferences

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 androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


        loadData()

        bt_button.setOnClickListener {
            saveData()
        }
    }

    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)
        }.apply()

        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.


Solution

  • Just use this?

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

    also when setting the text:

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