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)
Related
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.
I have a PreferenceFragment that contains 1 setting. It is defined (and called) with the following code :
class SettingsFragment : PreferenceFragmentCompat() {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.settings, rootKey);
loadSettings()
}
private fun loadSettings() {
val sp = PreferenceManager.getDefaultSharedPreferences(this.context)
val safemode = sp.getBoolean("safemode", false)
}
}
The fragment pops up normally and everything is good, but I do not have good understanding of SharedPreferences (I tried reading tutorials but I couldn't get it).
How do I store and use the settings in other fragments?
Actually SharedPreferences is for store small data (preferred strings) in it.
Technically it is XML file that save key value type of data.
You can have your SharedPreferences as static and use it every where you want.
To obtain shared preferences, use the following method In your Application/Activity/Fragment:
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app.test", Context.MODE_PRIVATE);
To read preferences:
String dummyKey = "dummyKey";
String l = prefs.getString(dummyKey, "default value");
To edit and save preferences
String dt = getSomeString();
prefs.edit().putString(dummyKey, dt).apply();
commit() return true if value saved successfully otherwise false. It save values to SharedPreferences synchronously.
apply() was added in 2.3 and doesn't return any value either on success or failure. It saves values to SharedPreferences immediately but starts an asynchronous commit.
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.
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.
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
}