When opening my app a dialog is always shown that closes when you press "Ok", I would like it to only be shown the first time they open the app, this is my code:
val miDialogo = AlertDialog.Builder(this)
miDialogo.setTitle(R.string.dialogo_titulo)
miDialogo.setMessage(R.string.dialogo_mensage)
miDialogo.setPositiveButton("Ok", null)
val dialog = miDialogo.create()
dialog.show()
You can save a boolean in SharedPreferences and check it before showing the dialogue if user saw it once switch it to false.
fun isFirstRun() {
var prefs_name = "MyPrefsFile"
var isFirst = false
var prefs: SharedPreferences = getSharedPreferences(prefs_name, MODE_PRIVATE)
var isFirst: Boolean = prefs.getBoolean(prefs_name, false)
if (isFirst) {
//Show the dialogue
prefs.edit().putInt(prefs_name,
false).apply();
}
}
Related
I have 2 radio buttons on my user registration page. If the user has registered by clicking the first radio button, I want to open the page according to him when he opens the application again, and if he has registered by clicking the second radio button, I want to show the page accordingly. How can I do that ?
class SignUpPage : AppCompatActivity() {
private lateinit var binding: ActivitySignUpPageBinding
private lateinit var auth : FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivitySignUpPageBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
auth = Firebase.auth
}
fun loginSignUp (view: View){
val name = binding.nameText.text.toString()
val surname = binding.surnameText.text.toString()
val email = binding.emailText.text.toString()
val password = binding.PasswordText.text.toString()
val button = binding.radioButton4.isChecked
val button2 = binding.radioButton5.isChecked
if(name.equals("")|| surname.equals("")|| email.equals("") || password.equals("") || button.equals("") || button2.equals("")) {
Toast.makeText(this,"Lütfen Tüm Alanları Doldurun.",Toast.LENGTH_SHORT).show()
}
else if (radioButton4.isChecked){
auth.createUserWithEmailAndPassword(email,password).addOnSuccessListener {
val intent = Intent(this#SignUpPage,AccetpActivity::class.java)
startActivity(intent)
finish()
}
}
else if(radioButton5.isChecked){
auth.createUserWithEmailAndPassword(email, password).addOnSuccessListener {
val intent = Intent(this#SignUpPage,MainActivity::class.java)
startActivity(intent)
finish()
}.addOnFailureListener {
Toast.makeText(this#SignUpPage,it.localizedMessage,Toast.LENGTH_SHORT).show()
}
}
}
}
You can store value of radio button which selected by user in Android Shared preferences.
When user reopen the app, check the value from preference in splash activity of your app and open activity as per value.
Shared pref ref: https://developer.android.com/training/data-storage/shared-preferences
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.
I have a Splash screen in my kotlin app, where I do some stuff like loading data. Currently it is only in german and I wanted to add english as additional language.
I've create the strings resources and so on.
Now I have added a bit of code to the Splash-Screen, where it checks, if the user already set a preferenced language (saved in sharedPreferences).
When there is nothing saved, a simple alertdialog pops up asking the user for his preference and sets everything accordingly.
Then the splashscreen is reloaded. When I choose english on my device (system language is german), the splash screen gets the correct string resources (english).
But when it changes to the MainActivity, it is german again. Only after restarting the app, everything is in english.
Here is how I change the language on my splashscreen:
private lateinit var mainIntent : Intent
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val prefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
var localeToSet: String? = prefs.getString("language", "")
if(localeToSet == null || localeToSet.equals("")){
val languages = arrayOf("Deutsch", "English")
val langSelectorBuilder = AlertDialog.Builder(this)
langSelectorBuilder.setTitle(R.string.selectLanguageText)
langSelectorBuilder.setCancelable(false)
langSelectorBuilder.setSingleChoiceItems(languages, -1) { dialog, selection ->
when(selection) {
0 -> {
localeToSet = "de"
setLocale("de")
}
1 -> {
localeToSet = "en"
setLocale("en")
}
}
recreate()
dialog.dismiss()
}.setOnDismissListener {
Handler().postDelayed({
startActivity(mainIntent)
finish()
}, SPLASH_TIME_OUT)
}
langSelectorBuilder.create().show()
}
else{
setLocale(localeToSet!!)
Handler().postDelayed({
startActivity(mainIntent)
finish()
}, SPLASH_TIME_OUT)
}
setContentView(R.layout.activity_splash_screen)
}
private fun createIntent(localeToSet: String){
mainIntent = Intent(this#SplashScreenActivity, MainActivity::class.java).apply {
//Do stuff and pass data to mainactivity
}
private fun setLocale(localeToSet: String) {
createIntent(localeToSet)
val config = resources.configuration
val locale = Locale(localeToSet)
Locale.setDefault(locale)
config.locale = locale
resources.updateConfiguration(config, resources.displayMetrics)
val prefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
val editor: SharedPreferences.Editor = prefs.edit()
editor.putString("language", localeToSet)
editor.apply()
}
Nevermind, found the issue:
val langSelectorBuilder = AlertDialog.Builder(this)
langSelectorBuilder.setTitle(R.string.selectLanguageText)
langSelectorBuilder.setCancelable(false)
langSelectorBuilder.setSingleChoiceItems(languages, -1) { dialog, selection ->
when(selection) {
0 -> {
localeToSet = "de"
setLocale("de")
}
1 -> {
localeToSet = "en"
setLocale("en")
}
}
recreate()
dialog.dismiss()
}.setOnDismissListener {
finish()
}
langSelectorBuilder.create().show()
Without starting the MainActivity here, it works like it should
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)
I wanna know that how can i retrieve different user information in a single activity.
In my case i have a ProfileActivity and i want that when i click on the profile button it retrieve my info from Firestore with my FirebaseAuth uid and when i search for another user and click on his profile it intent me the ProfileActivity so i did that , and it is working so fine, But the problem is that when i logout and login again my old information appears and when i click back button and after come back to the ProfileActivity now it show me my information, so i do not understand that why my info not shows me just after login.
private lateinit var profileId: String //initialization...
in onCreate...
firebaseUser= FirebaseAuth.getInstance().currentUser!!
val pref = getSharedPreferences("PREF", Context.MODE_PRIVATE)
if (pref != null)
{
this.profileId = pref.getString("profileId", "none").toString()
}
onStop...
override fun onStop() {
super.onStop()
val pref = getSharedPreferences("PREF", Context.MODE_PRIVATE)?.edit()
pref?.putString("profileId", firebaseUser.uid)
pref?.apply()
}
method to retrieve info as userInfo called in oncreate
private fun userInfo() {
val userRef = FirebaseFirestore.getInstance().collection("Users").document(profileId)
userRef.get()
.addOnSuccessListener { documentSnapshot ->
if (documentSnapshot != null && documentSnapshot.exists()) {
val user = documentSnapshot.toObject(User::class.java)
profile_fullname?.text = user.getFullname()
profile_about?.text = user.getAbout()
}
}
}
And this is how i intent from adapter to other user (profile activity).
holder.itemView.setOnClickListener {
val pref = mContext.getSharedPreferences("PREF", Context.MODE_PRIVATE).edit()
pref.putString("profileId", user.getUid())
pref.apply()
val intent = Intent(mContext, ProfileActivity::class.java )
mContext.startActivity(intent)
}
And this is logout operation
logoutButton.setOnClickListener {
FirebaseAuth.getInstance().signOut()
val intent = Intent(this#EditProfileActivity, LoginActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
finish()
}
You just have to share the preference value at the time of going to the profile activity like this
goToProfileActivityIcon.setOnClickListener {
val pref = mContext.getSharedPreferences("PREF", Context.MODE_PRIVATE).edit()
pref.putString("profileId", currentUserId)
pref.apply()
val intent = Intent(mContext, ProfileActivity::class.java )
mContext.startActivity(intent)
}
Where the goToProfileActivityIcon is the button which you are using to go switch to profile activity.
You'll need to clear the profileId from shared preferences when the user signs out:
logoutButton.setOnClickListener {
FirebaseAuth.getInstance().signOut()
val pref = getSharedPreferences("PREF", Context.MODE_PRIVATE)
if (pref != null) {
SharedPreferences.Editor editor = pref.edit();
editor.remove("profileId");
editor.apply();
}
val intent = Intent(this#EditProfileActivity, LoginActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
finish()
}