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()
Related
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
currently in work with my Own Weather API, it run on my own PC.
So i work with View Model and androidx.preference.PreferenceScreen.
I text is save with EditTextPreference.
But if i try to get that saved Strings out of SharedPref. and it Crash.
Here is the Companion Object Function that cause. CRash
fun
setServerAddress() : String {
val app = this as Application
val prefs = PreferenceManager.getDefaultSharedPreferences(app)
val ipInput = prefs.getString(app.getString(R.string.pref_Key_IP_Input), "")?.trim()
return ipInput.toString()
}
Well your code won't work because this as application will fail unless its actually an Application (which a companion object never is). The way to do this is to pass in a Context as a parameter:
setServerAddress(context: Context) : String {
val prefs = PreferenceManager.getDefaultSharedPreferences(context)
val ipInput = prefs.getString(app.getString(R.string.pref_Key_IP_Input), "")?.trim()
return ipInput.toString()
}
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)
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 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.