How to save a Checkbox state in android studio? - android

I'm new to android studio and I just can't figure out how to save the checkbox state using sharedpreference. If someone can help me I would greatly appreciate the assistance.
class SelectAlertSettings : AppCompatActivity() {
private lateinit var mp : MediaPlayer
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.select_alert_config)
}
fun onCheckboxClicked(view: View) {
if (view is CheckBox) {
val checked: Boolean = view.isChecked
when (view.id) {
R.id.checkbox_proximity_alert -> {
if (checked) {
val proximityAlert = R.raw.proximity_alert
mp = MediaPlayer.create(this, proximityAlert)
mp.start()
} else {
mp.stop()
}
}
}
}
val btnCancel : Button = findViewById(R.id.btnDone)
btnCancel.setOnClickListener{
finish()
}
}
}

To save a value to shared preferences, you need to do the following things:
Get a reference to the shared preferences object
Create a SharedPreferences.Editor instance
Choose the type you want to save in your shared preferences
Save the changes using commit or apply
You can read more about it here.
val sharedPref = activity?.getPreferences(Context.MODE_PRIVATE) ?: return
with (sharedPref.edit()) {
putBoolean("YOUR_CHECKBOX_KEY", checkboxState)
apply()
}

To save the check box state as a boolean in shared preferences do the following:
1 - Get a handle to shared preferences:
val sharedPref = activity?.getSharedPreferences("preferences file key",Context.MODE_PRIVATE)
2 - Write to shared preferences:
sharedPref.edit().putBoolean("key", value).apply()
3 - Read from shared preferences:
val value = sharedPref.getBoolean("key", defaultValue)
Read the documentation to learn more.
I also I recommend using DataStore instead of SharedPreferences. DataStore uses Kotlin coroutines and Flow to store data and it's the recommended way to save key-value pairs.

Related

passing a value through the edit text to be consulted in the GET of the interface

ok soo this is my interface code:
interface CodeService {
#GET("sro-rastro/{code}")
fun list(#Path("code") code : String = "LB524259080HK"
) : Call<Code>
}
And that is my activity getting the value from EditText
binding.btNewPackage.setOnClickListener {
var TrackingNumber = binding.etTrackingNumber.text.toString()
}
so, i want a way to get the value of TrackingNumber and pass it in the interface instead of String = "LB524259080HK"
it is my first time using Retrofit and i'm pretty lost at how i would pass the value to my interface.
I am not sure whether your structure is right calling the API from MainActivity instead of AddActivity because the EditText is defined there. Anyway, what you can do is use SharedPreferences to save the data of trackingNumber whenever btNewPackage is clicked like this:
binding.btNewPackage.setOnClickListener {
val trackingNumber = binding.etTrackingNumber.text.toString()
val sharedPref = getSharedPreferences("preference_file_key", Context.MODE_PRIVATE)
with (sharedPref.edit()) {
putString("tracking_number", trackingNumber)
apply()
}
}
And at the time of calling the API, you can simply fetch the trackingNumber using SharedPreferences and pass it along like this:
val sharedPref = getSharedPreferences("preference_file_key", Context.MODE_PRIVATE)
val trackingNumber = sharedPref.getString("tracking_number", "")
val call = RetrofitInitializer().codeService().list(trackingNumber)

How to save variable data in Kotlin

I'm trying to make this so that is saves every time I close the app. The tutorials I found are not clear for me, can anyone please assist me? If needed, here's how my variable I want saved is defined:
private var coins = 0
Here is the GitHub link if needed, which goes straight to MainActivity.
You can use shared preferences to save and retrieve simple data
save data
val sharedPref = activity?.getPreferences(Context.MODE_PRIVATE) ?: return
with (sharedPref.edit()) {
putInt("MY_COINS", coins)
apply()
}
Read data
val sharedPref = activity?.getPreferences(Context.MODE_PRIVATE) ?: return
val coins = sharedPref.getInt("MY_COINS"), defaultValue)
You can use Shared Preferences for state management or save data in key-value pair.
lateinit var shared : SharedPreferences
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_spactivity)
shared = getSharedPreferences("CoinsDB" , Context.MODE_PRIVATE)
var coins = 0
For Save
val edit = shared.edit()
edit.putInt("coins" , coins )
edit.apply()
For retrieve or read
val coinsValue = shared.getInt("coins")
I recommend using storage in files if that isn't a problem for you.

Saving and retrieving data in Android

private var highScore: Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_game)
loadData()
playGame()
}
override fun onDestroy() {
super.onDestroy()
saveData()
}
private fun saveData(){
val sharedPreferences = getSharedPreferences("sharedPrefs", Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
editor.apply{
putInt("INTEGER_KEY", highScore)
}.apply()
}
private fun loadData(){
val sharedPreferences = getSharedPreferences("sharedPrefs", Context.MODE_PRIVATE)
val savedInt = sharedPreferences.getInt("INTEGER_KEY", 0)
highScore = savedInt
binding.highScore.text = "Highscore: $savedInt"
}
I've made a simple game and I need to store the the highscore value and retrieve the value when the app is relaunched. I've tried to use sharedPreferences in the given code. But the highscore data is lost when I close the app and relaunch it. How can I save and retrieve the value?
PS: The highscore value is saved/retrieved properly when running the app in Android Studio's emulator. But it doesn't work when I run the app on my phone. It resets to 0 every time I relaunch it.
you are trying to save, when the app is destroyed. This might work sometimes, when onDestroy is actually called, but that does not happen for sure.
Apply is saving the data asynchronous to the disk, which won't happen as you are trying to do it when the app is destroyed. You have to use commit instead of apply to save the data synchronous.
I would recommend to save the data at another point of your app instead of in onDestroy, as this won't be called every time the app is closed/killed.

Looking for a way to persist user data

I need my users to be able to enter an API key in a "Setup" fragment and I need to use this API key in various other places such as other Fragments, Activities, Workers.
It is my understanding so far that getSharedPreferences is designed for this sort of purpose, much like the NSUserDefaults under iOS: save something somewhere, get it elsewhere.
Yet I can't seem to get the getSharedPreferences thing to work, I've had it initialized throughout the app with MainActivity.context but it always loses the data (the API key)
I am using ModelPreferencesManager https://gist.github.com/malwinder-s/bf2292bcdda73d7076fc080c03724e8a
I have an ApplicationState class as follows:
public class ApplicationState : Application() {
companion object {
// ...
lateinit var mContext: Context
var api_key : String = "undefined"
// ...
}
fun save(){
Log.e("ApplicationState", "save")
ModelPreferencesManager.with(mContext)
ModelPreferencesManager.put(api_key , key: "api_key_identifier")
}
fun load(){
Log.e("ApplicationState", "load")
ModelPreferencesManager.with(mContext)
api_key = ModelPreferencesManager.get<String>(key: "api_key_identifier") ?: "not read"
}
}
First, I store the application context on the first Activity (before anything else):
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
// ...
ApplicationState.mContext = applicationContext
// ...
}
}
I now expect to be able to save the api_key as follows:
ApplicationState.api_key = "blablah" // from some input in a random fragment
ApplicationState.save()
And to load it later:
ApplicationState.load()
var api_key = ApplicationState.api_key // in some activity or random fragment or worker
However it doesn't produce the expected result, the api_key is not saved (or loaded? can't figure out)
I have also tried using a JSON file but still no luck, looks like it either doesn't write/read or just gets deleted for some reason.
I could use a helping hand from someone more experienced as I am new to Android development and can't seem to find my way through these intricacies
I don't know what you are doing with your ModelPreferencesManager.
But this is the standard way to save something in preferences.
val sharedPref = requireContext().getSharedPreferences(keyPrefIdentifier,
Context.MODE_PRIVATE) //get shared preferences
val editor = sharedPref.edit() //make modifications to shared preferences
editor.putString("userApiKeyIdent", "theActualKey")
editor.apply() //save shared preferences persitent.
This is how you read them again.
val sharedPref = requireContext().getSharedPreferences(keyPrefIdentifier,
Context.MODE_PRIVATE)
val apiKey = sharedPref.getString("userApiKeyIdent", "defaultValue")
Edit: You are saving the api key as the identifiery for the preference. But get it as "api key "
It should look like this
fun save(){
Log.e("ApplicationState", "save")
ModelPreferencesManager.with(mContext)
ModelPreferencesManager.put("api_key ", api_key) //like this
}

How to save a score in Kotlin?

How can I save a score in my game scene even if I close the app and open it again? I'm new to android and I only know that in Swift things like that can be saved by using user defaults but I don't what to do in Android Studio.
Here is the score I want to save:
var score = 1
later in the scene ->
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
score =+ 2 //save the score here
}
If you want to use shared preferences, you can do the following:
Getting the shared preferences (if you only need one shared preferences file) instance by adding this code:
val sharedPref = activity?.getPreferences(Context.MODE_PRIVATE)
Write to shared preferences using:
sharedPref.edit()
putInt("Score", score)
commit()
Read from shared preferences using:
val score = sharedPref.getInt(getString("Score"), 0)

Categories

Resources