The sms code from firebase does not match - firebase

I created a number sending activity and confirmation/otp fragment using firebase phone auth. When directed to the confirmation page, a 6-digit sms code from Firebase is sent to the phone number entered, but no matter what I do, the entered edittext and the codes from firebase do not match.
When I leave the edit text blank, it redirects to the fragment I want as if it were correct. Can you help me where am I making a mistake? My codes in the confirmation fragment are as follows;
class FragmentRegisterTelOnay : Fragment() {
var comingNumber = ""
lateinit var auth : FirebaseAuth
lateinit var callbacks : PhoneAuthProvider.OnVerificationStateChangedCallbacks
var verificationID = ""
var comingCode : String = ""
override fun onCreateView(inflater: LayoutInflater,container: ViewGroup?,savedInstanceState: Bundle?): View? {
var view = inflater.inflate(R.layout.fragment_register_activity_phone,container,false)
view.tvKullaniciTelNo.setText("+90"+comingNumber)
auth = Firebase.auth
setupCallBack()
view.ileriButton.setOnClickListener {
if (comingCode.equals(editTextOnayKodu.text.toString())){
EventBus.getDefault().postSticky(EventBusDataEvents.KayitBilgileriniGonder("+90$comingNumber",null,verificationID,comingCode))
val transaction = requireActivity().supportFragmentManager.beginTransaction()
transaction.replace(R.id.telefonOnayKod,FragmentRegisterDetailPhone())
transaction.addToBackStack("TelOnayfragmentEklendi")
transaction.commit()}
else{
Toast.makeText(activity,"Wrong Code",Toast.LENGTH_LONG).show()
}
}
val options = PhoneAuthOptions.newBuilder(auth)
.setPhoneNumber("+90"+comingNumber) // Phone number to verify
.setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit
.setActivity(requireActivity()) // Activity (for callback binding)
.setCallbacks(callbacks) // OnVerificationStateChangedCallbacks
.build()
PhoneAuthProvider.verifyPhoneNumber(options)
return view
}
private fun setupCallBack() {
callbacks = object : PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
override fun onVerificationCompleted(credential: PhoneAuthCredential) {
if(!credential.smsCode.isNullOrEmpty()){
comingCode = credential.smsCode!!
progressBarOnayKod.visibility = View.GONE
Log.e("Success","on verificationcompleted sms: " + comingCode)}
else{
Log.e("Error","onverification has not completed")
}
}
override fun onVerificationFailed(e: FirebaseException) {
Log.e("Error: ",e.localizedMessage)
progressBarOnayKod.visibility = View.GONE
}
override fun onCodeSent(verificationId: String,token: PhoneAuthProvider.ForceResendingToken) {
verificationID = verificationId
progressBarOnayKod.visibility = View.VISIBLE
Log.e("Codesent","oncodesent worked")
}
}
}
#Subscribe (sticky = true)
internal fun onTelefonEvent(kayitBilgileri: EventBusDataEvents.KayitBilgileriniGonder){
comingNumber = kayitBilgileri.telNo.toString()
Log.e("test",comingNumber)
}
override fun onAttach(context: Context) {
super.onAttach(context)
EventBus.getDefault().register(this)
}
override fun onDetach() {
super.onDetach()
EventBus.getDefault().unregister(this)
}
}

first set the sha1 to firebase setting and generate google config.json then add to poject's root directory and add to build.gradle dependency.
it'll work properly
resources: https://github.com/firebase/quickstart-android/issues/283

Related

Android Firebase cannot download images and add them to a Bitmap Array

I am currently working on a matching card game where I need to store the images on Firebase. I am uploading the images by a button click when I start the game(doing it automatically creates same problem but the button one is safer) I think the Image isn't getting downloaded fast enough to show on the card face or it might not be working in a sequence with the whole app so the bitmap array gets zero elements inside. My current code is:
class game2x2 : AppCompatActivity() {
private lateinit var database: DatabaseReference
private lateinit var buttons: List<ImageButton>
//private lateinit var bitmapArray: ArrayList<Bitmap>
private var bitmapArray = mutableListOf<Bitmap>()
private lateinit var button1: ImageButton
private lateinit var button2: ImageButton
private lateinit var button3: ImageButton
private lateinit var button4: ImageButton
private lateinit var upload: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_game2x2)
val min = 1
val max = 45
val database = FirebaseDatabase.getInstance()
val imageID1 = Random().nextInt(max - min + 1) + min
val imageID2 = Random().nextInt(max - min + 1) + min
val aDatabase = FirebaseStorage.getInstance().getReference("all/$imageID1.jpg")
val sDatabase = FirebaseStorage.getInstance().getReference("all/$imageID2.jpg")
upload = findViewById(R.id.uploadButton)
button1 = findViewById(R.id.imageButton1)
button2 = findViewById(R.id.imageButton2)
button3 = findViewById(R.id.imageButton3)
button4 = findViewById(R.id.imageButton4)
buttons = listOf(button1, button2, button3, button4)
upload.setOnClickListener(View.OnClickListener {
try {
val localfile = File.createTempFile("tempfile", ".jpg")
aDatabase.getFile(localfile).addOnSuccessListener {
val bitmap = BitmapFactory.decodeFile(localfile.absolutePath)
bitmapArray.add(bitmap)
}.addOnFailureListener {
Log.w("myapplication", "ERROR RETRIEVING IMAGE")
Toast.makeText(this, "ERROR RETRIEVING IMAGE", Toast.LENGTH_SHORT).show()
}
} catch (e: Exception) {
e.printStackTrace()
}
try {
val localfile = File.createTempFile("tempfile1", ".jpg")
sDatabase.getFile(localfile).addOnSuccessListener {
val bitmap = BitmapFactory.decodeFile(localfile.absolutePath)
bitmapArray.add(bitmap)
}.addOnFailureListener {
Log.w("myapplication", "ERROR RETRIEVING IMAGE")
Toast.makeText(this, "ERROR RETRIEVING IMAGE", Toast.LENGTH_SHORT).show()
}
} catch (e: java.lang.Exception) {
e.printStackTrace()
}
/// DUPLICATE
bitmapArray.addAll(bitmapArray)
///SHUFFLE
bitmapArray.shuffle()
Log.w("myapplication", bitmapArray.size.toString())
})
buttons.forEachIndexed { index, button ->
button.setOnClickListener(View.OnClickListener {
button.setImageBitmap(bitmapArray[index])
})
}
}
}
Is there any other way to retrieve image from the Firebase Storage besides downloading and adding it to a temporary file and then decoding it to a bitmap?
I tried anything that I could find. I even tried adding the access tokens of the images to a realtime database and then getting them from there but I failed terribly. Thanks in advance for helping!
Since getFile() an asynchronous task I would imagine your log statement Log.w("myapplication", bitmapArray.size.toString()) is executing while the bitmapArray is still empty? This would happen because the aDatabase.getFile().addOnSuccessListener {} and sDatabase.getFile().addOnSuccessListener {} won't execute until the download finishes, but allow the rest of your function to continue to execute.
What you need to do is await the results of the downloads before continuing with the duplicate and shuffle portions.
getFile() returns a FileDownloadTask, which inherits from StorageTask. StorageTask has an isComplete() method -- and a few others the may be useful for errors cases. One option would be to capture the FileDownloadTask in a variable and not continue executing until your downloads are finished. However, be warned this might freeze up your main thread.
Edit: Instead of checking status on the main thread, you might want to try something like disabling the buttons until the images are ready. See edit comments:
class game2x2 : AppCompatActivity() {
private lateinit var database: DatabaseReference
private lateinit var buttons: List<ImageButton>
//private lateinit var bitmapArray: ArrayList<Bitmap>
private var bitmapArray = mutableListOf<Bitmap>()
private lateinit var button1: ImageButton
private lateinit var button2: ImageButton
private lateinit var button3: ImageButton
private lateinit var button4: ImageButton
private val numImages = 2 // EDIT total number of images we need to download
private val numImagesReady = AtomicInteger(0) // EDIT count of how many images are currently ready
private lateinit var upload: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_game2x2)
val min = 1
val max = 45
val database = FirebaseDatabase.getInstance()
val imageID1 = Random().nextInt(max - min + 1) + min
val imageID2 = Random().nextInt(max - min + 1) + min
val aDatabase = FirebaseStorage.getInstance().getReference("all/$imageID1.jpg")
val sDatabase = FirebaseStorage.getInstance().getReference("all/$imageID2.jpg")
upload = findViewById(R.id.uploadButton)
button1 = findViewById(R.id.imageButton1)
button2 = findViewById(R.id.imageButton2)
button3 = findViewById(R.id.imageButton3)
button4 = findViewById(R.id.imageButton4)
buttons = listOf(button1, button2, button3, button4)
// EDIT disable buttons until all images are ready
buttons.forEach {
it.setEnabled(false)
}
upload.setOnClickListener(View.OnClickListener {
try {
val localfile = File.createTempFile("tempfile", ".jpg")
aDatabase.getFile(localfile).addOnSuccessListener {
val bitmap = BitmapFactory.decodeFile(localfile.absolutePath)
bitmapArray.add(bitmap)
// EDIT add the image twice here instead of duplicating later
bitmapArray.add(bitmap)
// EDIT count this image as ready
val totalImagesReady = numImagesReady.incrementAndGet()
// EDIT once all images are ready, shuffle and enable the buttons
if (totalImagesReady == numImages) {
bitmapArray.shuffle()
buttons.forEach { it.setEnabled(true) }
}
}.addOnFailureListener {
Log.w("myapplication", "ERROR RETRIEVING IMAGE")
Toast.makeText(this, "ERROR RETRIEVING IMAGE", Toast.LENGTH_SHORT).show()
}
} catch (e: Exception) {
e.printStackTrace()
}
try {
// SUGGESTION especially if this will be implemented 8x8, you might want to try implementing this in a loop instead of duplicating code
val localfile = File.createTempFile("tempfile1", ".jpg")
sDatabase.getFile(localfile).addOnSuccessListener {
val bitmap = BitmapFactory.decodeFile(localfile.absolutePath)
bitmapArray.add(bitmap)
// EDIT add the image twice here instead of duplicating later
bitmapArray.add(bitmap)
// EDIT count this image as ready
val totalImagesReady = numImagesReady.incrementAndGet()
// EDIT once all images are ready, shuffle and enable the buttons
if (totalImagesReady == numImages) {
bitmapArray.shuffle()
buttons.forEach { it.setEnabled(true) }
}
}.addOnFailureListener {
Log.w("myapplication", "ERROR RETRIEVING IMAGE")
Toast.makeText(this, "ERROR RETRIEVING IMAGE", Toast.LENGTH_SHORT).show()
}
} catch (e: java.lang.Exception) {
e.printStackTrace()
}
// EDIT moved /// DUPLICATE
// EDIT refactor bitmapArray.addAll(bitmapArray)
// EDIT moved ///SHUFFLE
// EDIT moved bitmapArray.shuffle()
// EDIT remove Log.w("myapplication", bitmapArray.size.toString())
})
buttons.forEachIndexed { index, button ->
button.setOnClickListener(View.OnClickListener {
button.setImageBitmap(bitmapArray[index])
})
}
}
}

I'm trying to create a new firebase user, and upload the user data to firebase database, but when I try yo get the uid it's always null

I am trying to get the user uid after creating an account, so I can create a document on Firestore with the uid as document id. The problem is that I get only null, everything is working fine and I'm able to sign the user and receive the code but the uid is always null.
I know I'm accessing the uid before it's initialized because it takes time to restore the authentication state when the app starts so any idea how to wait for it until it's initialized?
First of all, if the data entered is correct then we call login() function, then we send the verification code, when the code is sent inside the onCodeSent(), the method we call uploadSelectedImageToFirebaseStorage() to upload the user image then we call saveUserToDatabase() function, and here is the problem. Inside the saveUserToDatabase() function, the UID is always null no matter what I tried, am I missing something?
#file:Suppress("DEPRECATION")
class SignUpActivity : AppCompatActivity() {
private lateinit var binding: ActivitySignUpBinding
private lateinit var auth: FirebaseAuth
private lateinit var callbacks: PhoneAuthProvider.OnVerificationStateChangedCallbacks
lateinit var storedVerificationId: String
lateinit var resendToken: PhoneAuthProvider.ForceResendingToken
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivitySignUpBinding.inflate(LayoutInflater.from(this))
auth = FirebaseAuth.getInstance()
setContentView(binding.root)
val flProfilePicture = binding.frameProfilePicture
val tilUserName = binding.tilUserName
val tilPhoneNumber = binding.tilPhoneNumber
val startButton = binding.startButton
val currentUser = auth.currentUser
if (currentUser != null) {
val intent = Intent(this#SignUpActivity, MainChatsActivity::class.java)
startActivity(intent)
finish()
}
callbacks = object : PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
override fun onVerificationCompleted(credential: PhoneAuthCredential) { }
override fun onVerificationFailed(e: FirebaseException) { }
override fun onCodeSent(
verificationId: String,
token: PhoneAuthProvider.ForceResendingToken,
) {
Toast.makeText(baseContext, "Code Sent", Toast.LENGTH_SHORT).show()
storedVerificationId = verificationId
resendToken = token
val intent = Intent(applicationContext, AuthenticatePhoneActivity::class.java)
intent.putExtra("storedVerificationId", storedVerificationId)
uploadSelectedImageToFirebaseStorage()
startActivity(intent)
finish()
}
}
flProfilePicture.setOnClickListener {
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
startActivityForResult(intent, 0)
}
startButton.setOnClickListener {
if (TextUtils.isEmpty(tilUserName.text.toString())) {
tilUserName.error = "Enter valid Name"
}
if (TextUtils.isEmpty(tilPhoneNumber.text.toString())) {
tilPhoneNumber.error = "Enter valid phone number"
} else {
val userName: String = tilUserName.text.toString()
val userPhoneNumber: String = tilPhoneNumber.text.toString()
login()
}
}
}
private var selectedProfilePicture: Uri? = null
#Deprecated("Deprecated in Java")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 0 && data != null) {
selectedProfilePicture = data.data
val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, selectedProfilePicture)
val flProfilePicture = binding.frameProfilePicture
val selectedCircleFrame = binding.selectedPictureCircleFrame
selectedCircleFrame.setImageBitmap(bitmap)
flProfilePicture.alpha = 0f
}
}
private fun login() {
val mobileNumber = binding.tilPhoneNumber
val number = mobileNumber.text.toString().trim()
if (number.isNotEmpty()) {
sendVerificationCode(number)
} else {
mobileNumber.error = "Enter a valid phone number"
}
}
private fun sendVerificationCode(number: String) {
val options = PhoneAuthOptions.newBuilder(auth)
.setPhoneNumber(number)
.setTimeout(60L, TimeUnit.SECONDS)
.setActivity(this)
.setCallbacks(callbacks)
.build()
PhoneAuthProvider.verifyPhoneNumber(options)
}
private fun uploadSelectedImageToFirebaseStorage() {
if (selectedProfilePicture == null) {
return
}
val fileName = UUID.randomUUID().toString()
val ref = FirebaseStorage.getInstance().getReference("/images/$fileName")
ref.putFile(selectedProfilePicture!!)
.addOnSuccessListener {
ref.downloadUrl.addOnSuccessListener {
it.toString()
Log.d("SignUpActivity", "image uploaded successfully")
saveUserToDatabase(it.toString())
}
}
.addOnFailureListener {
saveUserToDatabase(it.toString())
}
}
private fun saveUserToDatabase(profileImageUrl: String) {
val tilUserName = binding.tilUserName.text.toString()
val tilPhoneNumber = binding.tilPhoneNumber.text.toString()
val uid = FirebaseAuth.getInstance().uid.toString()
val database = Firebase.database("https://blend-4a9e4-default-rtdb.asia-southeast1.firebasedatabase.app")
val myRef = database.getReference("/users/$uid")
val user = User(uid, tilPhoneNumber, tilUserName, profileImageUrl)
Log.d("currentUser", uid)
myRef.setValue(user)
.addOnFailureListener {
Toast.makeText(baseContext, "Something went wrong, try again.", Toast.LENGTH_SHORT).show()
}
}
}

LazyColumn not update when data in LiveData update

I want to create chat app UI using ViewModel but when I send button the List in ViewModel update but LayzColumn not update it data. I don't know why it's not working.
My ChatViewModel
class ChatViewModel: ViewModel() {
private val _messages: MutableLiveData<MutableList<String>> = MutableLiveData(mutableListOf(""))
val messages: LiveData<MutableList<String>> get() = _messages
fun add(message: String) {
_messages.value?.add(message)
Log.d("Haha", "${_messages.value?.size}")
_messages.notifyObserver()
}
}
fun <T> MutableLiveData<T>.notifyObserver() {
this.value = value
}
My LazyColumn
val messages by chatViewModel.messages.observeAsState(mutableListOf(""))
LazyColumn(modifier = Modifier
.fillMaxWidth()
.weight(1f)
) {
items(messages.toList()) { message ->
SenderChat(message = message)
}
}

Firebase Custom Google Auth Login

I need to login users with Google Sign On onto Firebase. But since I need to use the Calendar API, I have to do a custom login (and not the one provided through Firebase on default), as I need the Oauth refresh token - which is not provided by Firebase. I have looked at the docs but none seem to work, I am using the below code as of now... can anybody suggest how do I use the token obtained from Google to login/register with Firebase?
private const val TAG = "WelcomeActivity"
class WelcomeActivity : AppCompatActivity() {
var firebaseUser: FirebaseUser? = null
//For Google Sign In
val RC_SIGN_IN: Int = 9001
private lateinit var mGoogleSignInClient: GoogleSignInClient
lateinit var mGoogleSignInOptions: GoogleSignInOptions
private lateinit var firebaseAuth: FirebaseAuth
private var firebaseUserID: String = ""
private lateinit var refUsers: DatabaseReference
//get data from google signin in handlesigninresult
private var googleId = ""
private var googleFirstName = ""
private var googleLastName = ""
private var googleEmail = ""
private var googleProfilePicURL = ""
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_welcome)
// //For google sign in
// configureGoogleSignIn()
// setupUI()
// enablePersistence()
firebaseAuth = FirebaseAuth.getInstance()
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken("")
.requestEmail()
.build()
mGoogleSignInClient = GoogleSignIn.getClient(this, gso)
google_login.setOnClickListener {
signIn()
}
login_welcome.setOnClickListener {
val intent = Intent(this#WelcomeActivity, LoginActivity::class.java)
startActivity(intent)
finish()
}
}
private fun signIn() {
val signInIntent = mGoogleSignInClient.signInIntent
startActivityForResult(signInIntent, RC_SIGN_IN)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == RC_SIGN_IN) {
val task =
GoogleSignIn.getSignedInAccountFromIntent(data)
handleSignInResult(task)
}
}
private fun handleSignInResult(completedTask: Task<GoogleSignInAccount>) {
try {
val account = completedTask.getResult(
ApiException::class.java
)
// Signed in successfully
googleId = account?.id ?: ""
Log.i("Google ID", googleId)
googleFirstName = account.givenName ?: ""
Log.i("Google First Name", googleFirstName)
googleLastName = account?.familyName ?: ""
Log.i("Google Last Name", googleLastName)
googleEmail = account?.email ?: ""
Log.i("Google Email", googleEmail)
val googleIdToken: String = account?.idToken ?: ""
Log.i("Google ID Token", googleIdToken)
googleProfilePicURL = account?.photoUrl.toString()
Log.i("Google Profile Pic URL", googleProfilePicURL)
firebaseAuthWithGoogle(googleIdToken)
} catch (e: ApiException) {
// Sign in was unsuccessful
Log.e(
"failed code=", e.statusCode.toString()
)
}
}
private fun enablePersistence() {
// [START rtdb_enable_persistence]
Firebase.database.setPersistenceEnabled(true)
// [END rtdb_enable_persistence]
}
private fun firebaseAuthWithGoogle(idToken: String) {
val credential = GoogleAuthProvider.getCredential(idToken, null)
firebaseAuth.signInWithCredential(credential)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success")
firebaseUserID = firebaseAuth.currentUser!!.uid
refUsers = FirebaseDatabase.getInstance().reference.child("Users").child(firebaseUserID)
refUsers.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(p0: DataSnapshot) {
if (p0.exists()) {
val user: Users? = p0.getValue(Users::class.java)
//Check if user exists in the database
if (user!!.getFirstName() != null) {
val intent = Intent(
this#WelcomeActivity,
IntroSplashScreen::class.java
)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
finish()
} else {
val usersHashMap = HashMap<String, Any>()
usersHashMap["uid"] = firebaseUserID
usersHashMap["firstname"] = googleFirstName
usersHashMap["surname"] = googleLastName
usersHashMap["profile"] = googleProfilePicURL
usersHashMap["primaryEmail"] = googleEmail
usersHashMap["search"] =
googleFirstName.toLowerCase(Locale.ROOT)
refUsers.updateChildren(usersHashMap)
.addOnCompleteListener {
if (task.isSuccessful) {
val intent = Intent(
this#WelcomeActivity,
NewProfileData::class.java
)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
finish()
}
}
}
}
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.exception)
// ...
}
// ...
}
}
private fun refreshIdToken() {
// Attempt to silently refresh the GoogleSignInAccount. If the GoogleSignInAccount
// already has a valid token this method may complete immediately.
//
// If the user has not previously signed in on this device or the sign-in has expired,
// this asynchronous branch will attempt to sign in the user silently and get a valid
// ID token. Cross-device single sign on will occur in this branch.
mGoogleSignInClient.silentSignIn()
.addOnCompleteListener(
this
) { task -> handleSignInResult(task) }
}
override fun onStart() {
super.onStart()
//Checks if the Google IDToken has expired, if yes it refreshes by SilentSign in and generates new Firebase Token
refreshIdToken()
//Checks if user is logged in to firebase
firebaseUser = FirebaseAuth.getInstance().currentUser
//If logged in then sends to MainActivity
if (firebaseUser != null) {
startActivity(IntroSplashScreen.getLaunchIntent(this))
finish()
}
}
override fun onResume() {
super.onResume()
refreshIdToken()
}
}
My method of checking if the user exists was incorrect with the currect process being to put the check on Datasnapshot exits or not. If exists then login else register.

how does onAuthStateChange() works and it's code in kotlin?

I am trying to log a message when there is a change in state, but apparently it's not working, I am not sure where I am going wrong.
I want to update the UI when the state is changed to user logged in, but for starters I am only trying to log a message.
I also don't quiet understand the registering it and unregistering it.
This is my login activity's code.
val TAG = "LoginActivity"
//private var mDatabaseReference: DatabaseReference? = null
//private var mDatabase: FirebaseDatabase? = null
// Firebase refferences for Authentication.
private var mAuth: FirebaseAuth? = null
private var mUser : FirebaseUser? = null
private var mDatabase : DatabaseReference? = null
private var mAuthListener : FirebaseAuth.AuthStateListener? = null
//global variables
private var emailString : String? = null
private var passwordString : String? = null
// ActivityState : ONCREATE.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
// initializing firebase Auth and database Reference.
mAuth = FirebaseAuth.getInstance()
mDatabase = FirebaseDatabase.getInstance().reference
// getting the currently logined user.
mUser = mAuth?.currentUser
//[START auth_state_listener]
FirebaseAuth.AuthStateListener { firebaseAuth ->
val cuser = firebaseAuth.currentUser
if(mUser != null) {
Log.d("WOWOWOWOWO : ", "you dont girl!")
}
}
}
//ActivityState : ONSTART.
override fun onStart() {
super.onStart()
mAuth?.addAuthStateListener(mAuthListener!!)
}
//ActivityState : ONPAUSE.
override fun onPause() {
super.onPause()
}
// function for when the login button is clicked.
// TODO : Login Activity : Function# 1.
fun loginBtnClicked(view : View) {
emailString = loginEmailTxt.text.toString()
passwordString = loginPasswordtxt.text.toString()
if(!emailString.isNullOrEmpty() && !passwordString.isNullOrEmpty()) {
// Checking if the login cridentials are correct. and then changing the Auth State to logged in.
//TODO : Login Activity : Function# 3.
mAuth!!.signInWithEmailAndPassword(emailString!!, passwordString!!).addOnCompleteListener(this) { task ->
if(task.isSuccessful) {
// User ID token retrival TODO: not sure what to do with the token yet.
mUser!!.getIdToken(true)
.addOnCompleteListener(OnCompleteListener {task: Task<GetTokenResult> ->
if(task.isSuccessful) {
var idToken = task.getResult().token
Log.d(TAG, "signInWithEmail:success :" + idToken)
} else {
}
})
} else {
Log.e(TAG, "signInWithEmail:failure", task.exception)
Toast.makeText(this#LoginActivity, "Authentication failed. Make sure email and password are correct",
Toast.LENGTH_SHORT).show()
}
}
} else {
Toast.makeText(this, "Email or Password can not be empty.", Toast.LENGTH_LONG).show()
}
}
// TODO : Login Activity : Function#2
fun getHelpImgClicked(view : View) {
val builder = AlertDialog.Builder(this)
val dialogView = layoutInflater.inflate(R.layout.get_help_dialog, null)
builder.setView(dialogView)
.setNegativeButton("Close" ){ _, _ -> }.show()
}
You're never assigning a non-null value to your mAuthListener. This is the only time it's assigned:
private var mAuthListener : FirebaseAuth.AuthStateListener? = null
And this is where you pass that null value to become an auth state listener:
override fun onStart() {
super.onStart()
mAuth?.addAuthStateListener(mAuthListener!!)
}
You also create an auth state listener, but never assign that object anywhere, so it doesn't do anything:
//[START auth_state_listener]
FirebaseAuth.AuthStateListener { firebaseAuth ->
val cuser = firebaseAuth.currentUser
if(mUser != null) {
Log.d("WOWOWOWOWO : ", "you dont girl!")
}
}
Did you mean to take that AuthStateListener object and assign it to mAuthListener during onCreate()?

Resources