My application crash when I logout from Firebase. I checked the logcat and it shows me the following stack trace.
io.reactivex.exceptions.UndeliverableException: java.lang.Throwable: Permission denied
at io.reactivex.plugins.RxJavaPlugins.onError(RxJavaPlugins.java:349)
at io.reactivex.internal.operators.observable.ObservableCreate$CreateEmitter.onError(ObservableCreate.java:74)
at messenger.tarang.com.messenger.allusers.AllUsers$loadUsers$1$1.onCancelled(AllUsers.kt:78)
at com.google.android.gms.internal.zzecw.zza(Unknown Source)
at com.google.android.gms.internal.zzehy.zzbyc(Unknown Source)
at com.google.android.gms.internal.zzeig.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:742)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:5527)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
Caused by: java.lang.Throwable: Permission denied
at messenger.tarang.com.messenger.allusers.AllUsers$loadUsers$1$1.onCancelled(AllUsers.kt:78)
at com.google.android.gms.internal.zzecw.zza(Unknown Source)
at com.google.android.gms.internal.zzehy.zzbyc(Unknown Source)
at com.google.android.gms.internal.zzeig.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:742)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:5527)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
Here is the code where the problem arises.
Observable.create<DataSnapshot>{ emitter ->
databaseReference
?.child("Users")
?.addChildEventListener(object : ChildEventListener{
override fun onCancelled(p0: DatabaseError?) {
if(!emitter.isDisposed){
emitter.onError(Throwable(p0.message))
}
}
override fun onChildMoved(p0: DataSnapshot?, p1: String?) {
}
override fun onChildChanged(p0: DataSnapshot?, p1: String?) {
}
override fun onChildAdded(p0: DataSnapshot?, p1: String?) {
if(!emitter.isDisposed)
emitter.onNext(p0!!)
}
override fun onChildRemoved(p0: DataSnapshot?) {
}
})
}.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : Observer<DataSnapshot>{
override fun onComplete() {
}
override fun onNext(t: DataSnapshot) {
val userModel = t.getValue(UserModel::class.java)
userModel?.uid = t.key
userAdapter?.addData(userModel!!)
}
override fun onSubscribe(d: Disposable) {
compositeDisposable?.add(d)
}
override fun onError(e: Throwable) {
e.printStackTrace()
}
})
Below is my Account Settings class where i am performing logout action.If i comment emitter.onError()in above code then i don't get any exceptions.
class AccountSettings internal constructor(): AppCompatActivity(), View.OnClickListener {
var toolbar : Toolbar ?= null
var toolbar_text : TextView ?= null
var logout_text : TextView ?= null
var firebaseAuth : FirebaseAuth ?= null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.account_settings)
initialize()
}
override fun onStart() {
super.onStart()
logout_text?.setOnClickListener(this)
}
fun initialize(){
firebaseAuth = FirebaseAuth.getInstance()
logout_text = findViewById(R.id.logout_text)
toolbar = findViewById(R.id.toolbar)
toolbar_text = toolbar?.findViewById(R.id.toolbar_text1)
toolbar_text?.setText("Account Settings")
toolbar_text?.visibility= View.VISIBLE
setSupportActionBar(toolbar)
}
fun logout() {
try {
firebaseAuth?.signOut()
displayMessage("logout successfully")
goToMainActivity()
}
catch(ex : Exception){
ex.printStackTrace()
displayMessage("you are not connected to Internet")
}
}
fun goToMainActivity() {
var intents = Intent (this,CheckAuthenticate::class.java)
intents.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intents)
finish()
}
fun displayMessage(message: String) {
Toast.makeText(this,message,Toast.LENGTH_SHORT).show()
}
override fun onClick(p0: View?) {
when(p0?.id){
R.id.logout_text ->{
logout()
}
}
}
override fun onDestroy() {
super.onDestroy()
}
}
What should i do to make it work? How should i properly handle this exception so that my application does not crash? Please help anyone...
You need to handle UndeliverableException. Add to your Application onCreate():
RxJavaPlugins.setErrorHandler(error -> {
//Log error or just ignore it
});
Related
I thought when response.body()?.let {} run, enrollBookAdapter (or booklist = it.books as mutableList<book>) would be initialized but, it did not... What am I doing wrong? How can I initailize bookList with Books...
class EnrollBookActivity : AppCompatActivity() {
private lateinit var binding: ActivityEnrollBookBinding
private lateinit var bookService: BookService
private lateinit var bookList:MutableList<Book>
private lateinit var enrollBookAdapter: EnrollBookAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityEnrollBookBinding.inflate(layoutInflater)
setContentView(binding.root)
initBookService()
bookServiceLoadBestSellers()
binding.selfBtn.setOnClickListener{
startActivity(Intent(this,SelfWriteActivity::class.java))
}
enrollBookAdapter.setOnBookClickListener(object:EnrollBookAdapter.OnBookClickListener{
override fun onBookClick(position: Int, book: Book) {
val intent = Intent(this#EnrollBookActivity,TalerMain::class.java)
intent.putExtra("title",enrollBookAdapter.bookList[position].title)
intent.putExtra("url",enrollBookAdapter.bookList[position].title)
startActivity(intent)
}
})
}
private fun initBookRecyclerView(bookList: MutableList<Book>) {
enrollBookAdapter = EnrollBookAdapter(bookList)
enrollBookAdapter.setOnBookClickListener(object:EnrollBookAdapter.OnBookClickListener{
override fun onBookClick(position: Int, book: Book) {
val intent = Intent(this#EnrollBookActivity,TalerMain::class.java)
intent.putExtra("title",enrollBookAdapter.bookList[position].title)
intent.putExtra("url",enrollBookAdapter.bookList[position].title)
startActivity(intent)
}
})
binding.bookRv.layoutManager = GridLayoutManager(this,2)
binding.bookRv.adapter = EnrollBookAdapter(bookList)
binding.bookRv.addItemDecoration(DividerItemDecoration(this, LinearLayoutManager.VERTICAL))
}
private fun bookServiceLoadBestSellers() {
bookService.getBestSellerBooks(getString(R.string.interparkAPIKey))
.enqueue(object : Callback<BestSellerDto> {
override fun onResponse(
call: Call<BestSellerDto>,
response: Response<BestSellerDto>
) {
if (response.isSuccessful.not()) {
Log.e(M_TAG, "NOT!! SUCCESS")
return
}
response.body()?.let {
Log.d(M_TAG, it.toString())
it.books.forEach { book ->
Log.d(M_TAG, book.toString())
}
//enrollBookAdapter = EnrollBookAdapter(it.books as MutableList<Book>)
initBookRecyclerView(it.books as MutableList<Book>)
//setRecyclerView(it.books)
}
}
override fun onFailure(call: Call<BestSellerDto>, t: Throwable) {
Log.e(M_TAG, t.toString())
}
})
}
}
Error
"java.lang.RuntimeException: Unable to start activity ComponentInfo{com.clone.practice/com.clone.practice.EnrollBookActivity}: kotlin.UninitializedPropertyAccessException: lateinit property enrollBookAdapter has not been initialized"
I thought when response.body()?.let {} run, enrollBookAdapter (or booklist = it.books as mutableList<book>) would be initialized but, it did not... What am I doing wrong? How can I initialize bookList with Books...
Try to add initBookRecyclerView before enrollBookAdapter.setOnBookClickListener(object:EnrollBookAdapter.OnBookClickListener line in onCreate.
After that uncomment enrollBookAdapter = EnrollBookAdapter(it.books as MutableList<Book>) and comment the next line.
just remove this code from your onCreate method only as you are trying to use enrollBookAdapter variable before initialisation which is causing crash .
And you have already set this method in initBookRecyclerView method so no need in onCreate method
enrollBookAdapter.setOnBookClickListener(object:EnrollBookAdapter.OnBookClickListener{
override fun onBookClick(position: Int, book: Book) {
val intent = Intent(this#EnrollBookActivity,TalerMain::class.java)
intent.putExtra("title",enrollBookAdapter.bookList[position].title)
intent.putExtra("url",enrollBookAdapter.bookList[position].title)
startActivity(intent)
}
})
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
When i run my app its showing me (InstantiationException:has no zero argument constructor) and ask for create a zero argument constructor, I am new in kotlin please suggest me how i can solve it.
Login Activity:-
class LoginActivity(val ViewModelProvider: Any) : AppCompatActivity(), AuthListenner {
private val listview: ListView? = null
private val progressBar: ProgressBar? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
}
override fun onStarted() {
toast("Login Started")
}
override fun onSuccess(logingResponse: LiveData<String>) {
toast("Login Success")
}
override fun onFailure(message: String) {
toast(message)
}
}
This is my Model Class:-
class AuthViewModel() : ViewModel() {
var username: String? = null
var password:String? = null
var authListenner: AuthListenner? = null
fun onLoginButtonClick(View: View){
authListenner?.onStarted()
if (username.isNullOrEmpty() || password.isNullOrEmpty()){
authListenner?.onFailure("Invalid username or password")
return
}
val logingResponse = UserRepository().userLogin(username!!, password!!)
authListenner?.onSuccess(logingResponse)
}
}
class UserRepository {
fun userLogin(username: String, password: String) : LiveData<String> {
val loginResponse = MutableLiveData<String>()
MyApi().userLogin(username, password)
.enqueue(object : Callback<ResponseBody> {
override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
loginResponse.value = t.message
}
override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
if (response.isSuccessful){
loginResponse.value = response.body()?.string()
}else{
loginResponse.value = response.errorBody()?.string()
}
}
})
return loginResponse
}
}
interface AuthListenner {
fun onStarted()
fun onSuccess(logingResponse: LiveData<String>)
fun onFailure(message: String)
}
Can't add para to the AppCompatActivity, it should be
class LoginActivity: AppCompatActivity(), AuthListenner {
//...
}
I am trying to test myself in android development. For that I am trying to make a social media app with the help of firebase (using firebase authentication), but the problem is. After I login with every credentials correct, its is not showing the next activity screen which is meant to be opened. I don't know what mistake did I make. Here is the code for loginAcitivity screen:
class LoginActivity : AppCompatActivity() {
private val firebaseAuth = FirebaseAuth.getInstance()
private val firebaseAuthListener = FirebaseAuth.AuthStateListener {
val user = firebaseAuth.currentUser?.uid
user?.let {
startActivity(HomeActivity.newIntent(this))
finish()
}
}
#SuppressLint("ClickableViewAccessibility")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
setTextChangeListener(emailET, emailTIL)
setTextChangeListener(passwordET, passwordTIL)
loginProgressLayout.setOnTouchListener { v :View, event :MotionEvent -> true }
}
private fun setTextChangeListener(et: EditText, til: TextInputLayout) {
et.addTextChangedListener(object: TextWatcher{
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
}
override fun afterTextChanged(s: Editable?) {
til.isErrorEnabled = false
}
})
}
fun onLogin(v: View){
var proceed = true
if(emailET.text.isNullOrEmpty()){
emailTIL.error = "Email is required"
emailTIL.isErrorEnabled = true
proceed = false
}
if(passwordET.text.isNullOrEmpty()){
passwordTIL.error ="Password is required"
passwordTIL.isErrorEnabled = true
proceed = false
}
if(proceed){
loginProgressLayout.visibility = View.VISIBLE
firebaseAuth.signInWithEmailAndPassword(emailET.text.toString(), passwordET.text.toString())
.addOnCompleteListener { task: Task<AuthResult> ->
if (!task.isSuccessful) {
loginProgressLayout.visibility = View.GONE
Toast.makeText(this#LoginActivity, "Login error: Either the username or password is wrong.", Toast.LENGTH_SHORT).show()
}
}.addOnFailureListener{e: Exception ->
e.printStackTrace()
loginProgressLayout.visibility = View.GONE
}
}
}
fun goToSignUp(v: View){
startActivity(SignUpActivity.newIntent(this))
finish()
}
override fun onStart() {
super.onStart()
firebaseAuth.addAuthStateListener { firebaseAuthListener }
}
override fun onStop() {
super.onStop()
firebaseAuth.removeAuthStateListener { firebaseAuthListener }
}
companion object{
fun newIntent(context: Context) = Intent(context, LoginActivity::class.java)
}
}
To test out that authentication is working or not I place a button in the activity to logout.
Help me please it's been week since I am stuck on it.
You were using lambda and in there you were no doing any task.
override fun onStart() {
super.onStart()
firebaseAuth.addAuthStateListener(firebaseAuthListener)
}
override fun onStop() {
super.onStop()
firebaseAuth.removeAuthStateListener(firebaseAuthListener)
}
I have a function for the user's login.
But it is suspended.
I try to get its return value, but I can't.
Here's what I tried to do
Code
class LoginViewModel #ViewModelInject constructor(private val remoteDataSource: OrderRemoteDataSource) :
ViewModel() {
private fun areValidCredentials(username: String?, password: String?): Boolean {
return username != null && password != null && username.length > 4 && password.length > 4
}
suspend fun login(username: String?, password: String?): Boolean {
return suspendCoroutine { it ->
val valid = areValidCredentials(username, password)
if (valid) {
// call finish so login activity won't show up after back button clicked in home fragment
try {
viewModelScope.launch {
//TODO CHECK if error code
val loginResponse =
remoteDataSource.login(LoginRequest(username!!, password!!))
if (loginResponse.status == Resource.Status.SUCCESS) {
val jwtToken = loginResponse.data?.jwtToken
if (!jwtToken.isNullOrEmpty()) {
sessionManager.saveAuthToken(jwtToken!!)
//ERROR!
it.resume(true)
}
}
}
} catch (e: Exception) {
Log.i("[LoginActivity]", e.localizedMessage!!)
it.resume(false)
e.printStackTrace()
}
} else {
Toast.makeText(
LOGIN_ACTIVITY,
"Username and password must be at least 5 letters long",
Toast.LENGTH_SHORT
).show()
}
it.resume(false)
}
}
}
And i call it
#AndroidEntryPoint
class LoginFragment : Fragment() {
private val mViewModel: LoginViewModel by viewModels()
private lateinit var navController: NavController
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return inflater.inflate(R.layout.frg_login, container, false)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.d("[LoginFragment]", "onCreate fun started!")
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
navController = findNavController()
loginButton.setOnClickListener {
//TODO navigate to new fragmnet
lifecycleScope.launch {
mViewModel.login(
loginUsernameText.text.toString(),
loginPasswordText.text.toString()
)
}
}
}
And i have error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: ru.gkomega.navigation, PID: 11863
java.lang.IllegalStateException: Already resumed
at kotlin.coroutines.SafeContinuation.resumeWith(SafeContinuationJvm.kt:45)
at ru.gkomega.maumarket.ui.login.LoginViewModel$login$$inlined$suspendCoroutine$lambda$1.invokeSuspend(LoginViewModel.kt:40)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.DispatchedTask.run(Dispatched.kt:241)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) I/chatty:
uid=10163(ru.gkomega.navigation) identical 16 lines W/mega.navigatio:
Got a deoptimization request on un-deoptimizable method
java.lang.Class java.lang.Class.classForName(java.lang.String,
boolean, java.lang.ClassLoader) I/Process: Sending signal. PID: 11863
SIG: 9 Disconnected from the target VM, address: 'localhost:58264',
transport: 'socket'
I don't know much about coroutines so they're probably the problem
You are resuming the coroutine regardless of the request happened or not, it failed or not.
suspend fun login(username: String?, password: String?): Boolean = suspendCoroutine { cont ->
if (areValidCredentials(username, password)) {
try {
viewModelScope.launch {
val loginResponse = remoteDataSource.login(LoginRequest(username!!, password!!))
val jwtToken = loginResponse.data?.jwtToken
if (loginResponse.status == Resource.Status.SUCCESS && !jwtToken.isNullOrEmpty()) {
sessionManager.saveAuthToken(jwtToken!!)
cont.resume(true)
} else cont.resume(false) // <-- Don't forget
}
} catch (e: Exception) {
Log.i("[LoginActivity]", e.localizedMessage!!)
cont.resume(false)
e.printStackTrace()
}
} else {
Toast.makeText(
LOGIN_ACTIVITY,
"Username and password must be at least 5 letters long",
Toast.LENGTH_SHORT
).show()
cont.resume(false) // <-- Put it right here.
}
// cont.resume(false) // <-- Not here
}
Try this code!
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
navController = findNavController()
loginButton.setOnClickListener {
//TODO navigate to new fragment
val isAuth = mViewModel.login(
loginUsernameText.text.toString(),
loginPasswordText.text.toString()
)
if (isAuth) {
val startMainAction =
LoginFragmentDirections.actionStartMain(loginUsernameText.text.toString())
navController.navigate(startMainAction)
}
}
}
And this fragment on viewModel
fun login(username: String?, password: String?): Boolean {
var isAuth = false
val valid = areValidCredentials(username, password)
if (valid) {
// call finish so login activity won't show up after back button clicked in home fragment
try {
//TODO CHECK if error code
runBlocking {
val loginResponse = remoteDataSource.login(LoginRequest(username!!, password!!))
if (loginResponse.status == Resource.Status.SUCCESS) {
val jwtToken = loginResponse.data?.jwtToken.toString()
if (!jwtToken.isNullOrEmpty()) {
sessionManager.saveAuthToken(jwtToken)
isAuth = true
}
}
}
} catch (e: Exception) {
Log.i("[LoginActivity]", e.localizedMessage!!)
e.printStackTrace()
}
I'm not sure if this code is correct, but it works!
Hello I am getting this exception continuously on launch of app :
2019-02-18 16:33:14.735 2080-2080/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: assus.oumayma.com.firebasekotlinapp, PID: 2080
java.lang.RuntimeException: Unable to start activity ComponentInfo{assus.oumayma.com.firebasekotlinapp/assus.oumayma.com.firebasekotlinapp.MainActivity}: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process assus.oumayma.com.firebasekotlinapp. Make sure to call FirebaseApp.initializeApp(Context) first.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2725)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2786)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1501)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:173)
at android.app.ActivityThread.main(ActivityThread.java:6459)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:938)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:828)
Caused by: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process assus.oumayma.com.firebasekotlinapp. Make sure to call FirebaseApp.initializeApp(Context) first.
at com.google.firebase.FirebaseApp.getInstance(com.google.firebase:firebase-common##16.0.2:240)
at com.google.firebase.auth.FirebaseAuth.getInstance(Unknown Source)
at assus.oumayma.com.firebasekotlinapp.MainActivity.onCreate(MainActivity.kt:23)
at android.app.Activity.performCreate(Activity.java:6673)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1136)
and this the code:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mAuth = FirebaseAuth.getInstance()
signOut.setOnClickListener {
view: View? -> mAuth.signOut()
startActivity(Intent(this, PhoneAuthenfication::class.java))
Toast.makeText(this, "Logged out Successfully :)", Toast.LENGTH_LONG)
.show()
}
}
override fun onStart() {
super.onStart()
if (mAuth.currentUser == null) {
startActivity(Intent(this, PhoneAuthenfication::class.java))
} else {
Toast.makeText(this, "Already Signed in :)", Toast.LENGTH_LONG).show()
}
}
}
class PhoneAuthenfication : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_phone_authenfication)
mAuth = FirebaseAuth.getInstance()
veriBtn.setOnClickListener { view: View? ->
progress.visibility = View.VISIBLE
verify()
}
authBtn.setOnClickListener { view: View? ->
progress.visibility = View.VISIBLE
authenticate()
}
}
private fun verificationCallbacks() {
mCallbacks = object : PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
override fun onVerificationCompleted(credential: PhoneAuthCredential) {
progress.visibility = View.INVISIBLE
signIn(credential)
}
override fun onVerificationFailed(p0: FirebaseException?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onCodeSent(verfication: String?, p1: PhoneAuthProvider.ForceResendingToken?) {
super.onCodeSent(verfication, p1)
verificationId = verfication.toString()
progress.visibility = View.INVISIBLE
}
}
}
private fun verify() {
verificationCallbacks()
val phnNo = phnNoTxt.text.toString()
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phnNo,
60,
TimeUnit.SECONDS,
this,
mCallbacks
)
}
private fun signIn(credential: PhoneAuthCredential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener { task: Task<AuthResult> ->
if (task.isSuccessful) {
toast("Logged in Successfully :)")
startActivity(Intent(this, MainActivity::class.java))
}
}
}
private fun authenticate() {
val verifiNo = verifiTxt.text.toString()
val credential: PhoneAuthCredential = PhoneAuthProvider.getCredential(verificationId, verifiNo)
signIn(credential)
}
private fun toast(msg: String) {
Toast.makeText(this, msg, Toast.LENGTH_LONG).show()
}
the build.gradle:
implementation 'com.google.firebase:firebase-auth:16.1.0'
implementation 'com.google.firebase:firebase-core:16.0.7'
You are trying to get an instance of Firebase without initialise it. Please add this line of code before you try to get an instance of Firebase:
FirebaseApp.initializeApp(this);
If you are using google service 4.1.0
classpath 'com.google.gms:google-services:4.1.0'
then update the version to
classpath 'com.google.gms:google-services:4.2.0'