1

There are two classes MainActivity and PickTimeForNotif in my project. In MainActivity getSharedPreferences works just fine, i can save my data and get it back. In PickTimeForNotif, however, the same method seems to do nothing.

Here's my simplified MainActivity class:

class MainActivity : AppCompatActivity(), ChangeCupDialogFragment.StringListener {
    @SuppressLint("SetTextI18n")
    
    //this is variable i'm saving
    private var drankToday = 0
    
    //function in which i save my value to SharedPreferences
    private fun saveWaterCountToInternalStorage(clickCounter: Int) {
        val sharedPref = this.getSharedPreferences("something", Context.MODE_PRIVATE)
        with (sharedPref.edit()){
            putInt(getString(R.string.clickCount), clickCounter)
            apply()
        }
    }
    
    //and here i get it from there
    private fun loadWaterCountToInternalStorage(): Int {
        val sharedPref = this.getSharedPreferences("something", Context.MODE_PRIVATE)
        return sharedPref.getInt(getString(R.string.clickCount), drankToday)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.main_activity)
        val setupNotifButton = findViewById<Button>(R.id.setupNotifButton)

        setupNotifButton.setOnClickListener{
            val notifIntent = Intent(applicationContext, PickTimeForNotif::class.java)
            startActivity(notifIntent)
        }

    }
}

In setOnClickListener i intend my second activity PickTimeForNotif, here it is.

class PickTimeForNotif: AppCompatActivity(), TimePickerFragment.OnCompleteListener {
    val APP_PREFERENCES = "settings"
    private val SAVED_FROM_HOUR = "SetFromHour"
    private var FROM_HOUR = 99

    private fun saveTimeToInternalStorage(prefName1: String, Hour:Int) {
        val sharedPref = this.getSharedPreferences(APP_PREFERENCES, MODE_PRIVATE)
        with (sharedPref.edit()){
            putInt(prefName1, Hour)
            apply()
        }
    }

    private fun loadTimeFromInternalStorage() {
        val sharedPref = this.getSharedPreferences(APP_PREFERENCES, MODE_PRIVATE)
        if (sharedPref.contains(APP_PREFERENCES)) {
            sharedPref.getInt(SAVED_FROM_HOUR, FROM_HOUR)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.pick_time_activity)
        saveTimeToInternalStorage(SAVED_FROM_HOUR, 1)
        loadTimeFromInternalStorage()
        Toast.makeText(applicationContext,"$FROM_HOUR", Toast.LENGTH_SHORT).show()
    }
}

In the code above i'm trying to set value (1 for example ) to a SAVED_FROM_HOUR key and then get it back and assign to FROM_HOUR variable. However, the Toast shows 99, which means that new data wasn't loaded properly. I tried putting all code from loadTimeFromInternalStorage and saveTimeToInternalStorage to onCreate, but the result is same.

I also tried checking if the Preferences file exists after i call getSharedPreferences with

if (sharedPref.contains(APP_PREFERENCES))

but it does not.

So i'm asking to explain what am i doing wrong and why i can save the data in my MainActivity, but not in the second one. Thanks alot to anyone in advance!!

gydroponch
  • 13
  • 5
  • `if (sharedPref.contains(APP_PREFERENCES))` is definitely going to prevent it from working. That function tells you if the SharedPreferences file you have *already opened* contains an entry with that key. You never added a preference using `APP_PREFERENCES` as a key--that's the name of your preferences file as a whole. So the code inside the if statement will never be reached. There's no reason to check if the file exists. The SharedPreferences instance itself is the connection to the existing file. – Tenfour04 May 23 '22 at 14:55
  • 1
    Also, I dont see that you have assigned the variable again – Sambhav Khandelwal May 23 '22 at 14:59
  • @Tenfour04 Thanks! Removed that line, still not working though. I also tried doing the same operations in onCreate method (but without `if (sharedPref.contains(APP_PREFERENCES))`) after setting content view, but it doesn't work :( Some other problem is still there – gydroponch May 23 '22 at 15:00

1 Answers1

2

In loadTimeFromInternalStorage(), you are fetching the value but not assigning to variable like this:

private fun loadTimeFromInternalStorage() {
        val sharedPref = this.getSharedPreferences(APP_PREFERENCES, MODE_PRIVATE)
        if (sharedPref.contains(APP_PREFERENCES)) {
            FROM_HOUR = sharedPref.getInt(SAVED_FROM_HOUR, FROM_HOUR)
        }
    }

Also, in this line FROM_HOUR = sharedPref.getInt(SAVED_FROM_HOUR, FROM_HOUR), the last parameter in getInt() method is the default value so you should make another constant for it or supply it 0.

Abu bakar
  • 751
  • 1
  • 4
  • 16
  • 1
    I missed this because `FROM_HOUR` is in all caps, but it's not a constant. @gydroponch, by convention, all-caps names are reserved only for constants. – Tenfour04 May 23 '22 at 15:02
  • 1
    @UndefinedBug1.0, thank you so much! I completely forgot that `getInt` just returns the value and i have to assign it to variable, so i just straight copypasted my own code from first activity and didn't do anything with retrieved value. Also had to delete `if (sharedPref.contains(APP_PREFERENCES))`, it was blocking the following code from executing – gydroponch May 23 '22 at 15:13