How to implement sharedPreferences in a Fragment in Kotlin - android

I'm trying to save data from my fragment in Kotlin, I tried to use shared preference for that since I'm only saving strings in the fragment. I don't understand why the data is not saving. I'm using them both in OnViewCreated.
First Fragment IMAGE [1]: https://i.stack.imgur.com/uqlUt.png
Second Fragment Image [2]: https://i.stack.imgur.com/ifpRU.png
FirstFragment
val sharedPreferences =
requireActivity().applicationContext.getSharedPreferences("sharedPref",Context.MODE_PRIVATE)
val price = sharedPreferences.getString("PRICE",null)
binding.priceId.text = price
val expense = sharedPreferences.getString("EXPENSE",null)
binding.priceId1.text = expense
Second Fragment with EditText
val insertedText : String = binding.itemPrice.text.toString()
val insertedText2 : String = binding.itemPrice2.text.toString()
val sharedPreferences = requireActivity().applicationContext.getSharedPreferences("sharedPref",Context.MODE_PRIVATE)
val editor : SharedPreferences.Editor = sharedPreferences.edit()
editor.apply {
putString("PRICE",insertedText)
putString("EXPENSE",insertedText2)
}
editor.apply()
Toast.makeText(requireContext(),"Saved", Toast.LENGTH_LONG).show()

Here's how I'm using sharedPreferences with fragment
//Getting the sharedPreferences
val appContext = requireContext().applicationContext
var prefs = appContext.getSharedPreferences("sharedPref", Context.MODE_PRIVATE)
prefs.edit().putString("PRICE", insertedText).apply();

Related

How to use sharedpref.edit() only once

I have a code where I called sharedPref.edit() and sharedPref.apply() multiple times. How to make convert it to call only once.
if (success) {
val data = response.getJSONObject("data")
sharedPreferences.edit().putBoolean("isLoggedIn", true).apply()
sharedPreferences.edit()
.putString("user_id", data.getString("user_id")).apply()
sharedPreferences.edit().putString("name", data.getString("name"))
.apply()
sharedPreferences.edit().putString("email", data.getString("email"))
.apply()
sharedPreferences.edit()
.putString("mobile_number", data.getString("mobile_number"))
.apply()
sharedPreferences.edit()
.putString("address", data.getString("address")).apply()
StyleableToast.Builder(this)
.text("Welcome " + data.getString("name"))
.backgroundColor(Color.RED)
.textColor(Color.WHITE).show()
userSuccessfullyLoggedIn()
}
I want to use the method call only once.
This can be called once, the returned editor instance can be stored in
a variable and re-used.
How to do this ??
These little steps will organize your code.
You can put it like this:
val editor = sharedPreferences.edit()
Then use it :
editor.putBoolean("isLoggedIn", true)
And Add others values without ".apply()"
Then Put at the End:
editor.apply()
you can create your custom Shared Preferences
class CustomSharedPreferences {
companion object {
private val PREFERENCES_USER_NAME = "preferences_user_name"
private var sharedPreferences: SharedPreferences? = null
#Volatile private var instance: CustomSharedPreferences? = null
private val lock = Any()
operator fun invoke(context: Context) : CustomSharedPreferences = instance ?: synchronized(lock){
instance ?: makeCustomSharedPreferences(context).also {
instance = it
}
}
private fun makeCustomSharedPreferences(context: Context) : CustomSharedPreferences{
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
return CustomSharedPreferences()
}
}
fun saveUser(name: String, email: String){
sharedPreferences?.edit(commit = true){
putString(PREFERENCES_USER_NAME, name)
}
}
fun getUser() = sharedPreferences?.getString(PREFERENCES_USER_NAME, "")
}
You can save all information to SP in saveUser().

setting language before setContentView results in unending loop

I have a fragment with settings of an app that saves the user selected mode and language
( a bit of code:
binding.languageButton.setOnClickListener{
builder = AlertDialog.Builder(requireContext())
builder.setTitle(getString(R.string.setLanguage))
builder.setItems(langArray) { _, which ->
val sharedPref = requireActivity().getSharedPreferences("Settings", Context.MODE_PRIVATE).edit()
sharedPref.putString("LANGUAGE", langArray[which]).apply()
checkUserPreferences()
changeLanguage(langArray[which])
binding.languageButton.text = langArray[which]
}
builder.create()
builder.show()
}
}
private fun changeLanguage(language: String) {
if(language != binding.languageButton.text.toString()){
val local = Locale(language)
val dm = resources.displayMetrics
val con = resources.configuration
con.locale = local
resources.updateConfiguration(con, dm)
val refresh = Intent(
requireContext(),
MainActivity::class.java
)
refresh.putExtra(binding.languageButton.text.toString(), language)
startActivity(refresh)
}
}
and that part (as mentioned) saves mode and selected language to sharedPreferences that I later want to use in mainActivity and other fragments, and I've put in MainActivity:
private fun loadPreferences(){
val preferences = getSharedPreferences("Settings", Activity.MODE_PRIVATE)
Log.i(TAG, preferences.getString("LANGUAGE", "eng").toString())
Log.i(TAG, preferences.getInt("MODE", 1).toString())
val local = Locale(preferences.getString("LANGUAGE", "eng").toString())
val dm = resources.displayMetrics
val con = resources.configuration
con.locale = local
resources.updateConfiguration(con, dm)
val refresh = Intent(
this.baseContext,
MainActivity::class.java
)
refresh.putExtra(preferences.getString("LANGUAGE", "eng").toString(),
preferences.getString("LANGUAGE", "eng"))
startActivity(refresh)
}
and this is referenced in:
class MainActivity : AppCompatActivity() {
// TODO: IT'S THE ONE
companion object {
private const val TAG = "MainActivity"
private const val CHANNEL_ID = "plantz_app_channel_01"
private const val notificationId = 909
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
loadPreferences()
setContentView(R.layout.activity_main)
// ...
and after running the app It only shows the app logo and logs sharedPreferences but the app doesn't go any further, I've tried to tweak with it for a bit but It hasn't done much, any ideas what should I change to make it work?
Thanks in advance :)
This infinity loop happens because when the MainActivity is going to be opened you call loadPreferences() in onCreate method where you open a new instance of MainActivity from there.
So the infinity loop goes like below:
onCreate() method of MainActivity is called
loadPreferences() method is called
in loadPreferences() after you have set the language from SharedPreferences you start a new instance of your MainActivity which redirects you back to step 1.
To avoid this infinity loop remove the below lines from your loadPreferences() method:
val refresh = Intent(this.baseContext,MainActivity::class.java)
refresh.putExtra(preferences.getString("LANGUAGE", "eng").toString(), preferences.getString("LANGUAGE", "eng"))
startActivity(refresh)

check value exists or not using EncryptedSharedPreferences android

I use the EncryptedSharedPreferences to store value while login...i want to change text in navigation drawer of home activity
so when user is loggedin it will show logout else it will show login navigation drawer
Loginactivity:--------
sharedPreferences = EncryptedSharedPreferences.create(
"secret_shared_prefs",
masterKeyAlias,
baseContext,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
) as EncryptedSharedPreferences
while login im doing this
val editor = sharedPreferences.edit()
editor.putString("EmailId", edtEmailId)
editor.putString("password", edtPassword)
editor.apply()
checking in Homeactivity:---------
val menu: Menu = bind.navRightView.getMenu()
val nav_connection: MenuItem = menu.findItem(R.id.nav_login)
val sharedPreference =
applicationContext.getSharedPreferences("secret_shared_prefs", Context.MODE_PRIVATE)
val value: String = sharedPreference.getString("EmailId", null).toString()
if(!sharedPreference.contains(value))
{
nav_connection.title = "Loginn"
}
else{
nav_connection.title = "Logout"
}
well output of this code is always having a title as loginn that means it detecting value as null
need help for EncryptedSharedPreferences thanks
You are adding the values but not saving them to SharedPreferences.
You should be using commit() or apply().
Do this:
val editor = sharedPreferences.edit()
editor.putString("EmailId", edtEmailId)
editor.putString("password", edtPassword)
editor.apply() // Important
I also see that you are calling
val sharedPreference = applicationContext.getSharedPreferences("secret_shared_prefs", Context.MODE_PRIVATE)`
which gives you the normal SharedPreference, I guess.
You should be using:
val sharedPreferences = EncryptedSharedPreferences.create(
"secret_shared_prefs",
masterKeyAlias,
baseContext,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
) as EncryptedSharedPreferences
Then check if the email address is empty or not.
if(!sharedPreference.contains("EmailId")
nav_connection.title = "Loginn"
else
nav_connection.title = "Logout"

How To Make Multiple TextViews Show The Value Of An Edited SharedPreference Each Time In Kotlin

I Have Created A Function That Dynamically Makes A Textview And Assigns The Values Of Shared Preferences To It.Now I Want To Make A New TextView Each Time The User Enters Data In It
There are 5 Shared Preferences - Day , Medicine ,Time , HowMuch ,When
val shrd = getSharedPreferences("Add$dayselected", Context.MODE_PRIVATE)
val editor = shrd.edit()
editor.putString("medicine", medicine)
editor.putString("day", dayselected)
editor.putString("whenSelected", whenselected)
editor.putString("medicineSelected", medicineselected)
editor.putString("time", timeselected)
editor.apply()
Toast.makeText(this#Add, "Saved To Internal Database", Toast.LENGTH_SHORT).show()
These Are The Preferences
val pref = getSharedPreferences("AddFriday", MODE_PRIVATE)
val dayA = pref?.getString("day", "NOT FOUND ").toString()
val medicinea = pref?.getString("medicine", "NOT FOUND ").toString()
val whenSel = pref?.getString("whenSelected", "NOT FOUND ").toString()
val mediselec = pref?.getString("medicineSelected", "NOT FOUND ").toString()
val time = pref?.getString("time", "NOT FOUND ").toString()
Now I Have Assigned The Value Of Each Preference To A TextView
If The User Enters New Data I Want The New Textview To Have The New Data And The Old To Remain The Same
Functions To add Textviews
private fun add_view(data: String, id: Int): View {
val text = TextView(applicationContext)
text.setBackgroundColor(Color.rgb(255, 229, 229))
text.width = 100
text.height = 50
text.x = 21F
text.y = 88F
text.id = id
text.text = data
return text
}
private fun add_row(dayA: String, medicinea: String, whenSel: String, mediselec: String, time: String) {
val layout: ConstraintLayout? = fridaylayout
val dayview = add_view(dayA, R.id.dayf)
val medicineview = add_view(medicinea, R.id.medicinef)
medicineview?.x = +100F
val whenselview = add_view(whenSel, R.id.whenf)
whenselview?.x = +200F
val mediselview = add_view(mediselec, R.id.howmuchf)
mediselview?.x = +300F
val timeview = add_view(time, R.id.timef)
timeview?.x = +400F
layout?.addView(dayview)
layout?.addView(medicineview)
layout?.addView(whenselview)
layout?.addView(mediselview)
layout?.addView(timeview)
}
Thank You
Asad

How to store 2D array in android shared preference in kotlin?

I want to store 2D array using shared preference ?
Here I am trying to store 2D array in shared preference from one activity and after that i can load it in another activity using previously stored 2D array but i am not able to store 2D array in shared preference.
val _rMsg = intent.getStringArrayExtra(rKey)
val inflater = getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val parent = _class11_
val _arData = arrayListOf<Array<String>>()
val sharedPreferences = getSharedPreferences("shared pref", Context.MODE_PRIVATE)
val gson = Gson()
val backJson = sharedPreferences.getString("task_li",null)
val type = TypeToken<ArrayList<>>() {}.type
_arData.add(gson.fromJson(backJson,type))
try {
_arData.add(_rMsg)
val edit = sharedPreferences.edit()
val json = gson.toJson(_arData)
edit.putString("task_li",json)
edit.apply()
for (i in _arData) {
val cardView = inflater.inflate(R.layout._preset_layout, null)
val mT = cardView.findViewById<TextView>(R.id._title__)
mT.text = i[0].toString()
parent.addView(cardView)
}
} catch (ex: Exception) {
}
We can use ObjectSerializer. [ https://github.com/apache/pig/blob/89c2e8e76c68d0d0abe6a36b4e08ddc56979796f/src/org/apache/pig/impl/util/ObjectSerializer.java ] this awesome class permit you to simple serialize and deserialize every kind of object, so you can simply save them as string into shared. You can store it like this :
val mArrayTest = arrayListOf<Array<String>>()
mArrayTest.add(arrayOf("1","3"))
mArrayTest.add(arrayOf("2","4"))
edit.putString("mArrayTest",ObjectSerializer.serialize(mArrayTest)).commit()
and get it like this :
val mTestStr = pref.getString("mArrayTest",null)
if (mTestStr != null) {
val mTestStr2 = ObjectSerializer.deserialize(mTestStr) as ArrayList<Array<String>>
Toast.makeText(this, mTestStr2[0][1].toString(), Toast.LENGTH_SHORT).show()
}

Categories

Resources