Hey Guys Im trying to push the user data in kotlin to firebase but when i click the create account button nothing happends here is the code for Create account class
class CreateAccount : AppCompatActivity() {
var mAuth:FirebaseAuth?=null
var mdata:DatabaseReference?=null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_create_account)
mAuth= FirebaseAuth.getInstance()
Createacc.setOnClickListener{
var email=acemail.text.toString().trim()
var pass=acpass.text.toString().trim()
var name=acname.text.toString().trim()
if(!TextUtils.isEmpty(email)||!TextUtils.isEmpty(name)||!TextUtils.isEmpty(pass)){
createAccount(email,pass,name)
}
else{
Toast.makeText(this,"Please fill all the details",Toast.LENGTH_LONG).show()
}
}
}
fun createAccount(email: String,password:String,dispname:String){
mAuth!!.createUserWithEmailAndPassword(email,password).addOnCompleteListener(this,{
task: Task<AuthResult> ->
if(task.isSuccessful){
var curruser=mAuth!!.currentUser
var userid=curruser!!.uid
Toast.makeText(this,"Building user wait",Toast.LENGTH_LONG).show()
var uobject=HashMap<String,String>()
uobject.put("Display_name",dispname)
uobject.put("Status","Hi I'm New")
uobject.put("image","default")
uobject.put("thumb image","default")
mdata=FirebaseDatabase.getInstance().reference.child("Users").child(userid)
mdata!!.setValue(uobject).addOnCompleteListener{
task:Task<Void> ->
if(task.isSuccessful){
Toast.makeText(this,"User Created",Toast.LENGTH_LONG).show()
}
else{
Toast.makeText(this,"OOPS!! User not Created",Toast.LENGTH_LONG).show()
}
}
}
})
}
}
Main problem is in create account function ,it is being called correctly but right after the createUserWithEmailAndPassword function the task is not successfull hence the if loop does not run. There nothing is printed in the toast Neither "User created " nor "OOPS not created" i dont know whats going on.
I have installed the firebase dependency and my app is connected to a firebase database.
Related
Can someone explain to me why this simple code is not working properly?
In the beginning I created an object with auth and currentUser
object FirebaseUtils {
val auth: FirebaseAuth = FirebaseAuth.getInstance()
val currentUser: FirebaseUser? = auth.currentUser
}
My login activity function
fun login(){
val email = binding.loginInput.text.toString()
val password = binding.passwordInput.text.toString()
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener {
task ->
if (task.isSuccessful){
task.result
Log.d("login_status", "Logged: ${currentUser?.uid}")
startActivity(Intent(this, MainActivity::class.java))
finish()
} else {
Log.d("login_status", task.exception.toString())
}
}
}
Start activity:
lifecycleScope.launch {
delay(2000)
if(currentUser?.uid != null){
Log.d("login_status", "Logged: ${currentUser.uid}")
startActivity(Intent(applicationContext, MainActivity::class.java))
}else{
startActivity(Intent(applicationContext, LoginMainActivity::class.java))
}
finish()
}
And sign out
fun signOut(){
auth.signOut()
startActivity(Intent(this, LoginMainActivity::class.java))
Log.d("login_status", "Signed out: ${currentUser?.uid}")
finish()
}
The problem is that after the first login I can see that logged user is null so my app is crashing (no data for the user). However, after restarting I am logged in as this user. I cant also sign out - activity changes to the login screen but even if I pass different credentials the user remains the same.
EDIT
When I log in and restart the app it works - the correct user is logged.
When I log out and restart the app it also works - the user is signed out.
So why is there a problem between activities
Your result is null because you are getting the result object out of the task object but you aren't doing anything with it. Simply calling:
task.result
Doesn't provide any benefit. However, you can save that result into a variable and call AuthResult#getUser() like this:
val user = task.result.getUser()
Log.d("login_status", "Logged: ${user?.uid}")
So right after you authenticate the user successfully, you'll be able to log the UID correctly.
I've been struggling with this problem for more than a week help me out if you know the fix.
enter image description here
I am trying to delete the data from a child node in the Realtime Firebase but it keeps regenerating even when I delete the token data.
This is my code:
when a user logs in an FCM token is generated automatically (onCreate).
when I try to log him out of his account I want the token to be deleted from the token list but it keeps regenerating even when I logout
this is the User fragment is redirected to after login:
val currentUser : String = firebaseAuth.currentUser?.uid.toString()
val databaseReference = FirebaseDatabase.getInstance("https://trial-38785-default-rtdb.firebaseio.com/")
.getReference("AppUsers").child("Doctor").child(currentUser)
FirebaseMessaging.getInstance().token.addOnCompleteListener {
if (it.isComplete) {
val firebaseToken = it.result.toString()
val myRef =
FirebaseDatabase.getInstance("https://trial-38785-default-rtdb.firebaseio.com/")
.getReference("AppUsers").child("Doctor").child(currentUser)
myRef.child("Token").orderByChild("token").equalTo(firebaseToken)
.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
val token : Token = Token(firebaseToken)
if (snapshot.exists()) {
return
} else {
databaseReference.child("Token")
.child(currentdate.toString()).setValue(token)
}
}
override fun onCancelled(error: DatabaseError) {
Toast.makeText(context, error.message, Toast.LENGTH_LONG).show()
}
})
}
}.addOnFailureListener {
Toast.makeText(context, it.message, Toast.LENGTH_LONG).show()
}
This is another fragment where the doctor logout.
pressing logout button this is the code i ran
val delRef = FirebaseDatabase.getInstance().getReference("AppUsers")
.child("Doctor").child(currentId.toString())
.child("Token").child(key.toString()).removeValue()
delRef.addOnSuccessListener {
println("Removed.")
}.addOnFailureListener {
println("Not Removed.")
}
When using the Query#addValueEventListener() method, it means that you are trying to listen for real-time updates. That being said, every change that takes place in the database and corresponds to your query, always triggers your onDataChange() method. Since when you are logging out, you remove a value from the query you are listening to, your token gets written again, hence that behavior. This is happening over and over again.
To solve this, simply change the above method call to Query#addListenerForSingleValueEvent(). This means that it listen for changes only once.
I finally figured out what I was doing wrong, I just had to move my code (myRef) outside of FirebaseMessaging.
I have an application where i register the user using phone number authentication , everything works fine but as the user is done verifying the phone number , i would like to push some credentials of the user to
realtime datbase , but the issue is that i'm not able to do so ... stuck basically , if any one could i'll appreciate it
This is my code
private fun signInWithAuthPhoneCredentials(credentials: PhoneAuthCredential) {
FirebaseAuth.getInstance().signInWithCredential(credentials)
.addOnCompleteListener {
if(it.isSuccessful){
// so basically if authentication is successful , i want to create a path to save user
// credentials which dosn't exist in the first place , upon checking if snapshot dosn't
// exist , i want to get user details and push them into database
// even with debugging , it gets to the last line of ( valueEventlister) and it stops
// there , it dson't even get to check wether snapshot exists or not
val currentUser = FirebaseAuth.getInstance().currentUser
if(currentUser != null){
val databaseReference = FirebaseDatabase.getInstance().reference.child("users").child(currentUser.uid)
databaseReference.addListenerForSingleValueEvent(object : ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
if(!snapshot.exists()){
val contactInfoMap = hashMapOf<String,Any>()
contactInfoMap["name"] = currentUser.displayName!!
contactInfoMap["phone"] = currentUser.phoneNumber!!
databaseReference.updateChildren(contactInfoMap)
}
userIsLoggedIn()
}
override fun onCancelled(error: DatabaseError) {
}
})
}
}
}
.addOnFailureListener {
Log.d("ERROR TAG","Error ${it.message}")
}
}
I am trying to set up the in app reviews in my app but just with a button click to show the app review dialogue. There is some limited info here: https://developer.android.com/guide/playcore/in-app-review/kotlin-java
However I am struggling to apply the logic in the docs to achieve my usecase.
Any help would be greatly appreciated.
For Kotliners.
In your Main Activity
private lateinit var reviewInfo: ReviewInfo
private lateinit var manager: ReviewManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setupReviewManager()
button.setOnClickListener{
val flow = manager.launchReviewFlow(this, reviewInfo)
flow.addOnCompleteListener { _ ->
Toast.makeText(this, "Thanks for your Review", Toast.LENGTH_SHORT).show()
}
}
}
private fun setupReviewManager(){
manager = ReviewManagerFactory.create(this)
val requestReview = manager.requestReviewFlow()
requestReview.addOnCompleteListener { request ->
if (request.isSuccessful) {
reviewInfo = request.result
} else {
Log.d("ReviewException", request.exception.toString())
}
}
}
Remember to test on a device with google play store, also
Note: The ReviewInfo object is only valid for a limited amount of time. Your app should request a ReviewInfo object ahead of time (pre-cache) but only once you are certain that your app will launch the in-app review flow.
Let me describe the application im trying to do using Kotlin, on Android Studio.
Splash Screen => Login Screen => Main App
Splash Screen: Just a photo
Login Screen: Provides different ways of logging (Google, Facebook, etc)
MainActivity: Allows you to log off, in that case, you must return to "Login Screen"
So far I have been working only with Facebook Login.
I managed to place the button, make it work, and get a proper uid. The trouble is that, when that button is clicked, it automatically switches to "Log Out". So, when I go back from my MainActivity to my Login Screen, instead of having the button to Login again, im having a "Log Out" button, when account is actually already logged out.
Is there a way to prevent this button from changing? I have been reading tons of documentation, but havent found anything useful.
Is my idea incorrect? Or is there a better way to do this?
Note that everytime I Leave the LoginScreen, I place a finish(). The reason of this was to try to reset the activity, and make it work as if the program was running from scratch.
Variables defined on LoginScreen
private var mCallBackManager : CallbackManager?= null
private var mFirebaseAuth : FirebaseAuth?= null
On create function
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.lay_login_screen)
//-----------Inicializadores-Facebook---------------
mFirebaseAuth = FirebaseAuth.getInstance()
FacebookSdk.sdkInitialize(getApplicationContext())
mCallBackManager = CallbackManager.Factory.create()
//--------------------------------------------------
//-----------Boton-Facebook-------------------------
Button_LoginScreen_LoginFace.setOnClickListener()
{
iniciarSesionFacebook();
}
//--------------------------------------------------
}
private fun iniciarSesionFacebook()
{
Button_LoginScreen_LoginFace.registerCallback(mCallBackManager, object : FacebookCallback<LoginResult>
{
override fun onSuccess(result: LoginResult?)
{
d(getString(R.string.TAG_FacebookLogin),"Login Correct")
handleFacebookToken(result!!.accessToken)
}
override fun onCancel()
{
d(getString(R.string.TAG_FacebookLogin),"Login cancelled")
}
override fun onError(error: FacebookException?)
{
d(getString(R.string.TAG_FacebookLogin),"Login Error")
}
})
}
private fun handleFacebookToken(accessToken: AccessToken?)
{
val credential = FacebookAuthProvider.getCredential(accessToken!!.token)
mFirebaseAuth!!.signInWithCredential(credential).addOnFailureListener()
{error->
d(getString(R.string.TAG_FacebookLogin),"Error 1"+error.message)
}
.addOnSuccessListener { resultado->
startActivity(Intent(this, MainActivity::class.java))
finish()
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?)
{
super.onActivityResult(requestCode, resultCode, data)
mCallBackManager!!.onActivityResult(requestCode,resultCode,data)
}
Finally, this is how I "Log Out" from MainActivity, and return to LoginScreen
class MainActivity : AppCompatActivity()
{
//----------Variables-Globales----------------
private var mFirebaseAuth : FirebaseAuth?= null
//--------------------------------------------
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//-------Inicializo-Variables------------------------
mFirebaseAuth = FirebaseAuth.getInstance()
//---------------------------------------------------
Button_MainActity_LogOf.setOnClickListener{
val firebaseaux=mFirebaseAuth
firebaseaux?.signOut()
startActivity(Intent(this, ActivityLoginScreen::class.java))
}
}
}
This is how the LoginScreen looks the first time is ran.
This is how it looks after manually logging of. Note that is not only the appearence of the code, the code itself changes. Now the button doesnt allow you to LogIn.
Just to add some extra information, i have found this property on the docs
Configuration: auto_logout_link
HTML5 Attribute: data-auto-logout-link
Description: If its activated, the button will be replaced by a LogOut button if the user has already logged in
Options: True,False
This es EXACTLY what im looking for. But, from what I can see, that is only ment for webpages and not android. Does somebody know how to touch this configuration in android? or the equivalent adroid option?
I will add the link where I found the property.
https://developers.facebook.com/docs/facebook-login/web/login-button/
Thanks in advance
Ok, after some time I managed to solve the Issue.
I was logging out from the Firebase Authentication, but not from Facebook authentication.
I didnt manage to stop the button from behaving like it does, but at least the behaviour now is correct.
I will share my new LogOut code.
Button_MainActity_LogOf.setOnClickListener{
FirebaseAuth.getInstance().signOut() //Log out from Firebase
if(isFacebookLogin()) //Check if logged in on facebook
{
LoginManager.getInstance().logOut() //Log out from facebook
}
//Here i should log out from other providers
startActivity(Intent(this, ActivityLoginScreen::class.java))
}
private fun isFacebookLogin(): Boolean
{
return AccessToken.getCurrentAccessToken() !=null
}