check value exists or not using EncryptedSharedPreferences android - 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"

Related

How to implement sharedPreferences in a Fragment in Kotlin

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();

How to remove values from Shared

I am working on android using kotlin, I have saved userId in shared preferences but when I try to remove it, it didn't removed. Am I doing it right?
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val id = item.itemId
if (id == R.id.action_settings) {
val pref = applicationContext.getSharedPreferences("Auth", Context.MODE_PRIVATE)
val editor: SharedPreferences.Editor = pref.edit()
editor.remove("UserId")
editor.commit()
Toast.makeText(this, "Sign out", Toast.LENGTH_SHORT).show()
}
return super.onOptionsItemSelected(item)
}
Login code, this is my fun which I am calling when user login and it is called like this:
saveUserIdSession(mAuth.currentUser.uid.toString())
fun saveUserIdSession(id: String) {
val sharedPreferences: SharedPreferences? =
this.activity?.getSharedPreferences("Auth", Context.MODE_PRIVATE)
var editor: SharedPreferences.Editor = sharedPreferences!!.edit()
editor.apply{
putString("UserId", id)
}.apply()
}
Deleting Android Shared Preferences in one line :-)
context.getSharedPreferences("Auth", 0).edit().clear().commit();
Thanks,
Programiner
Note:- Upvote Answer if Helpful.

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().

Localization not working after app restart

I'm including localization to translate my app intro three different languages, after setting up the translated strings of each language, I go to preference settings and I check a checkbox and and the translation works fine, the problem is that when I restart the app , localization even though I have saved the chosen language in sharedpreference and retreiving it in mainactivity
*This is how I'm setting the languages
var sharedPreferences = requireContext().getSharedPreferences("prefs",
Context.MODE_PRIVATE)
var editor = sharedPreferences.edit()
spanishCheckBox.setOnPreferenceChangeListener(object : Preference.OnPreferenceChangeListener{
override fun onPreferenceChange(preference: Preference?, newValue: Any?): Boolean {
var isSpanishChecked = newValue as Boolean
if(isSpanishChecked){
var Lang = "es"
editor.putString("key",Lang)
editor.apply()
var local = Locale(Lang)
var configuration = Configuration()
configuration.locale = local
resources.updateConfiguration(configuration,resources.displayMetrics)
englishCheckBox.isChecked = false
frenchCheckBox.isChecked = false
Intent(requireContext(),MainActivity::class.java).also {
it.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
startActivity(it)
}
}
return true
}
})
This is how i m retreiving data in mainactivity
fun LoadLanguageConfiguration(){
var sharedpreferences = getSharedPreferences("prefs", Context.MODE_PRIVATE)
var langCode = sharedpreferences.getString("key","")
var local = Locale(langCode)
var configuration = Configuration()
configuration.locale = local
baseContext.createConfigurationContext(configuration)
}
The translation only works when I set the language in the app, but when I restart the app, it goes back to default language which is English.
The problem is that I was not starting my language loading method at the start and before everything, so I put it as first method in my oncreate and everything works as supposed to.

App crashes on reading shared preferences after obfuscation

In my application, I am using SharedPreferences to store some user preferences. The application was not obfuscated (-dontobfuscate in the proguard file).
Now in the next version of the application, I want to enable obfuscation. When I try this, the application returns NullPointerException while reading the SharedPreferences data from the previous version of the application. The error log is not helpful because the code is already obfuscated and it does not provide meaningful information. However, while trying in the debug mode I found the crash may be due to null context which is a static variable in the code! That should not be the case because the application works file if SharedPreferences were not there already.
Is there any way the app can still read the SharedPreferences data from unobfuscated version?
Writing / reading the SharedPreferences is pretty standard:
Writing:
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor prefsEditor = mPrefs.edit();
prefsEditor.putString("userUnitsOption", "C");
//apply the storage
prefsEditor.apply();
Reading:
final SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(context);
return mPrefs.getString("userUnitsOption", "A");
If you want to use shared preferences in Android then use it as given below :
First, you have to store your preferences like this :
SharedPreferences.Editor editor = getSharedPreferences("mySharedPref", MODE_PRIVATE).edit();
editor.putString("myName", "abc");
editor.apply();
Now, To read or get those stored shared preferences write code as given below :
SharedPreferences prefs = MainActivity.this.getSharedPreferences("mySharedPref", MODE_PRIVATE); // Here MainActivity.this represent the context. So you can use your context in place of MainActivity.this
String strName = prefs.getString("myName","defaultName");
In Kotlin,
Usage:
private val sharedPref = defaultPrefs(this)
To Save Data--> sharedPref[KEY] = *String data to save*
To Get Data --> val userDetails = sharedPref[KEY, ""]
Create a shared preference helper class like below.
object PreferenceHelper {
fun defaultPrefs(context: Context): SharedPreferences =
PreferenceManager.getDefaultSharedPreferences(context)
fun customPrefs(context: Context, name: String): SharedPreferences =
context.getSharedPreferences(name, Context.MODE_PRIVATE)
inline fun SharedPreferences.edit(operation: (SharedPreferences.Editor) -> Unit) {
val editor = this.edit()
operation(editor)
editor.apply()
}
/**
* puts a key value pair in shared prefs if doesn't exists, otherwise updates value on given [key]
*/
operator fun SharedPreferences.set(key: String, value: Any?) {
when (value) {
is String? -> edit { it.putString(key, value) }
is Int -> edit { it.putInt(key, value) }
is Boolean -> edit { it.putBoolean(key, value) }
is Float -> edit { it.putFloat(key, value) }
is Long -> edit { it.putLong(key, value) }
else -> throw UnsupportedOperationException("Not yet implemented")
}
}
/**
* finds value on given key.
* [T] is the type of value
* #param defaultValue optional default value - will take null for strings, false for bool and -1 for numeric values if [defaultValue] is not specified
*/
inline operator fun <reified T : Any> SharedPreferences.get(
key: String,
defaultValue: T? = null
): T? {
return when (T::class) {
String::class -> getString(key, defaultValue as? String) as T?
Int::class -> getInt(key, defaultValue as? Int ?: -1) as T?
Boolean::class -> getBoolean(key, defaultValue as? Boolean ?: false) as T?
Float::class -> getFloat(key, defaultValue as? Float ?: -1f) as T?
Long::class -> getLong(key, defaultValue as? Long ?: -1) as T?
else -> throw UnsupportedOperationException("Not yet implemented")
}
}
}

Categories

Resources