How to use PreferenceFragment settings in other fragments? - android

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.

Related

Android shared preference, Kotlin

I have the following simple code. It takes the value of a textbox, saves it and retrieve.
The retrieved value is not the same as the saved one.
The printout:
value: qwert
asdf
What the problem could be?
val sharedPref = getSharedPreferences("Data", Context.MODE_PRIVATE)
sharedPref.edit().putString("Str",binding.text.editText?.text.toString())
print("Value: ")
println(binding.text.editText?.text.toString())
sharedPref.edit().commit()
println(sharedPref.getString("Str","asdf"))
Thank you for any hints in advance
SharedPreferences#edit hands you an instance of a SharedPreferences.Editor class on which you're calling the putString method but you're not committing any changes there.
Your second sharedPref.edit().commit() just gets a new instance of SharedPreferences.Editor without any editions and calls commit with no changes.
Try the following
val editor = sharedPrefs.editor()
editor.putString("key", "value")
editor.commit()
return sharedPrefs.getString("key", "defaultValue")
A more idiomatic approach would be to use the apply function from the kotlin stdlib:
sharedPrefs.edit().apply {
putString("key", "value")
commit()
}
You can also try like this
//For Add String Value in sharedPreferences
val sharedPreferences = getSharedPreferences("key", MODE_PRIVATE) ?: return
with(sharedPreferences.edit()) {
putString("yourStringKey", "Hello World")
apply()
}
//Here get enter string value from sharedPreferences other activity
val sharedPreferences1 = getSharedPreferences("key", MODE_PRIVATE) ?: return
val string = sharedPreferences1.getString("yourStringKey", "hi") //"hi" is default value
Log.e("sharedPreferences1", "sharedPreferences1 Val is -->> $string")
For More Information, you can refer to official android documentation here

How to save a Checkbox state in android studio?

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.

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 run a function from one class in another class in Android Studio [Kotlin]?

I am trying to save user preferences for language, so I have a preferences class with a setter and getter for language, as well as a separate Language activity where the user actually picks which language they want.
From this language activity, I want to use the setter to set the user's chosen language preference within the preferences class. Here is the preferences class:
class Preferences (context: Context) {
val PREFS_FILENAME = "artour.prefs"
val LANGUAGE = "language"
val prefs: SharedPreferences = context.getSharedPreferences(PREFS_FILENAME, Context.MODE_PRIVATE);
fun getLang() : String {
return prefs.getString(LANGUAGE, "english")
}
public fun setLang(lang:String) {
val editor = prefs.edit()
editor.putString(LANGUAGE, lang)
editor.apply()
}
}
How would I go about running the setLang method from the language activity?
I dont now if I'm missing anything in this question, but just do this:
val preferences = Preferences(this)
preferences.setLang("it is that easy")
in any function in your activity class.
What it does is create an object (val preferences = Preferences()) and then calling a method on it (preferences.setLang("this is a string")). Make sure to use an actual language identifier instead of a random string though.

Categories

Resources