Android shared preference, Kotlin - android

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

Related

Questions regarding sharedPreferences (Kotlin)

I am experimenting around with Kotlin's sharedPreferences, however I cannot seem to get the updated value to stick.
val sharedPreferences = getSharedPreferences("Files", Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
editor.putInt("numbers",1).apply()
val textview = findViewById<TextView>(R.id.textview)
textview.text = sharedPreferences.getInt("numbers",0).toString()
val button = findViewById<Button>(R.id.button)
button.setOnClickListener {
editor.putInt("numbers",2).apply()
textview.text = sharedPreferences.getInt("numbers",0).toString()
}
In the code above I set the initial value of the sharedPreference to 1, upon clicking the button the value will be updated to 2 and displayed.That works fine however when closing the app and reopening it, the value reverts to 1. Is there a way to permanatly keep the updated value?
You are setting it to that value every time you open the activity, since onCreate() is called every time it opens. You should check if the value is already set, and if it is, skip that line of code.
if ("numbers" !in sharedPreferences) {
val editor = sharedPreferences.edit()
editor.putInt("numbers",1).apply()
}
By the way, there is an extension function for editing without having to call apply and editor. repeatedly:
if ("numbers" !in sharedPreferences) {
sharedPreferences.edit {
putInt("numbers",1)
}
}

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.

How to use PreferenceFragment settings in other fragments?

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.

Method threw 'java.lang.NullPointerException' exception. Cannot evaluate java.time.LocalDateTime.toString()

In my android app with kotlin, i use a login interfece which I put Email and Password. After a success authetication, I want to stock this User with SharedPreferences.
The User has as attribute: birthday,lastlogin and registrationdate of type of "LocalDateTime" and others of type String.
The following function, is to set the user in sharedpreferences with keyvalue "lastUser" :
private val sharedPreferences: SharedPreferences =
context.getSharedPreferences(context.packageName, Context.MODE_PRIVATE)
fun setUserByKeyValue(key: String,user: UsersData?) {
val jsonString = Gson().toJson(user)
val editor = sharedPreferences.edit()
editor.putString(key, jsonString).apply()
}
The problem is here as the following with the localdatetime:
Method threw 'java.lang.NullPointerException' exception. Cannot evaluate java.time.LocalDateTime.toString()

Categories

Resources