Android Studio - Kotlin can't use firebase database - android

When I click "sign in button" I got
"W/System: Ignoring header X-Firebase-Locale because its value was null"
"D/TrafficStats: tagSocket(90) with statsTag=0xffffffff, statsUid=-1" in run tab
This is my signin page codes
package com.deniz.cywm
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.EditText
import android.widget.Toast
import com.deniz.cywm.databinding.ActivityMainBinding
import com.deniz.cywm.databinding.ActivityMainKayitOlBinding
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.FirebaseDatabase
class MainKayitOl : AppCompatActivity() {
private lateinit var auth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding: ActivityMainKayitOlBinding = ActivityMainKayitOlBinding.inflate(layoutInflater)
val view = binding.root
auth = FirebaseAuth.getInstance() /
setContentView(view)
binding.girisDon.setOnClickListener(){
intent = Intent(applicationContext,MainActivity::class.java)
startActivity(intent)
}
binding.kytButon.setOnClickListener(){
var kemail = binding.email.text.toString()
var ksifre = binding.sifre.text.toString()
auth.createUserWithEmailAndPassword(kemail, ksifre)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
Log.d("TAG", "createUserWithEmail:success")
val user = auth.currentUser
} else {
Log.w("TAG", "createUserWithEmail:failure", task.exception)
Toast.makeText(baseContext, "Authentication failed.",
Toast.LENGTH_SHORT).show()
}
}
}
}
}

Related

Firebase authentication issues, Kotlin

I am having some issues with Firebase auth. I'm building an app using using Kotlin but keep retrieving the error 'W/System: Ignoring header X-Firebase-Locale because its value was null.'
I had this working previously, when I had set up the application using activities. I've now moved towards MVP architecture, but this seems to have broken my firebase authentication. I have also ensured that Email/Password sign in method has been enabled in the Firebase console.
If anyone could please take a look and hopefully you can see where I am going wrong. Many thanks.
SignInView
package org.wit.hikingtrails.views.signIn
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import org.wit.hikingtrails.databinding.ActivitySignInBinding
import com.google.firebase.auth.FirebaseAuth
import org.wit.hikingtrails.activities.SignUpActivity
import org.wit.hikingtrails.views.hikeList.HikeListView
import org.wit.hikingtrails.views.signUp.SignUpView
class SignInView : AppCompatActivity() {
lateinit var presenter: SignInPresenter
private lateinit var binding: ActivitySignInBinding
private lateinit var firebaseAuth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
presenter = SignInPresenter( this)
super.onCreate(savedInstanceState)
binding = ActivitySignInBinding.inflate(layoutInflater)
setContentView(binding.root)
firebaseAuth = FirebaseAuth.getInstance()
binding.textView.setOnClickListener {
val intent = Intent(this, SignUpView::class.java)
startActivity(intent)
}
binding.button.setOnClickListener {
val email = binding.emailEt.text.toString()
val pass = binding.passET.text.toString()
if (email.isNotEmpty() && pass.isNotEmpty()) {
presenter.doLogin(email, pass)
} else {
Toast.makeText(this, "Empty Fields Are not Allowed !!", Toast.LENGTH_SHORT).show()
}
}
}
override fun onStart() {
super.onStart()
if(firebaseAuth.currentUser != null){
val intent = Intent(this, HikeListView::class.java)
startActivity(intent)
}
}
}
SignInPresenter:
package org.wit.hikingtrails.views.signIn
import android.content.ContentValues.TAG
import android.content.Intent
import android.util.Log
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import com.google.firebase.auth.FirebaseAuth
import org.wit.hikingtrails.views.hikeList.HikeListView
import timber.log.Timber
import timber.log.Timber.i
class SignInPresenter (val view: SignInView) {
private lateinit var loginIntentLauncher : ActivityResultLauncher<Intent>
init{
registerLoginCallback()
}
var auth: FirebaseAuth = FirebaseAuth.getInstance()
fun doLogin(email: String, pass: String) {
// view.showProgress()
auth.signInWithEmailAndPassword(email, pass).addOnCompleteListener(view) { task ->
if (task.isSuccessful) {
val launcherIntent = Intent(view, HikeListView::class.java)
loginIntentLauncher.launch(launcherIntent)
} else {
i("Login failed:")
// val launcherIntent = Intent(view, HikeListView::class.java)
// loginIntentLauncher.launch(launcherIntent)
}
// view.hideProgress()
}
}
private fun registerLoginCallback(){
loginIntentLauncher =
view.registerForActivityResult(ActivityResultContracts.StartActivityForResult())
{ }
}
}
For anyone that was having the same issue: The issue was with my API key. In kotlin, to debug, I used Timber.i( "signInWithCredential:failure ${task.exception?.message}") within the else statement of doLogin() in the presenter

Kotlin livedata observer not triggered

i'm practising a bit with kotlin and was testing Room and livedata, my app gets data from a json and the stores it in room, i want to move this network call to its own file and class, but if i do so the observer i set to get the changes don't trigger anymore, any help would be appreciated
here is a snipped of my mainactivity, if more is needed to know what happens please let me know
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import android.widget.Toast
import androidx.activity.viewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.viewModelScope
import androidx.room.Room
import com.optiva.videoplayer.data.*
import com.optiva.videoplayer.network.GetData
import com.optiva.videoplayer.network.Networking
import com.optiva.videoplayer.network.RetrofitConnect
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val dbcategories = Room.databaseBuilder(applicationContext, CategoriesDatabase::class.java,"categories.db").build()
val dbvideo = Room.databaseBuilder(applicationContext, VideosDatabase::class.java,"videos.db").build()
val retrofitData = RetrofitConnect.retrofitInst?.create(GetData::class.java)
val categoriesList = retrofitData?.getAll()
categoriesList?.enqueue(object: Callback<DataList> {
override fun onResponse(
call: Call<DataList>,
response: Response<DataList>
) {
val test = response?.body()
val cat = test?.categories
val vid = test?.videos
lifecycleScope.launch(Dispatchers.IO) {
if (cat != null) {
for(c in cat){
dbcategories.categoriesDAO().insertAll(CategoriesEntity(c.id,c.title,c.type))
}
}
if (vid != null) {
for(v in vid){
dbvideo.VideosDAO().insertAll(VideosEntity(v.id,v.thumb,v.videoUrl,v.categoryId,v.name))
}
}
}
}
override fun onFailure(call: Call<DataList>, t: Throwable) {
Toast.makeText(applicationContext,"error", Toast.LENGTH_LONG).show()
}
})
val textView: TextView = findViewById(R.id.test) as TextView
dbcategories.categoriesDAO().getALL().observeForever({categories ->
if(categories.size>0){
textView.text= categories[0].title
}
})
dbcategories.categoriesDAO().getALL().observe(this, {categories ->
if(categories.size>0){
textView.text= categories[0].title
}
}
} ```

my app keep crashing after tryed to connect it to firebase kotlin

I created a simple login and sup app and connect it to firebase.
so far the logging layout does not even show up it's just crushing while lanching which makes me so confused?
[![eroo message][1]][1]
this is my login/main activity
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
class MainActivity : AppCompatActivity() {
private lateinit var auth: FirebaseAuth
val button: Button = findViewById(R.id.buGotosub)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
auth = FirebaseAuth.getInstance()
button.setOnClickListener {
startActivity(Intent(this,SubscribAcc::class.java))
finish()
}
}
public override fun onStart() {
super.onStart()
// Check if user is signed in (non-null) and update UI accordingly.
val currentUser = auth.currentUser
updarUI(currentUser)
}
fun updarUI(currentUser : FirebaseUser?){
}
} ```

How can you add multiple users in a Kotlin Login?

I'm trying to figure out how to add more users in a Login app made with Kotlin, there's no database or whatever, the accounts are hardcoded into the program, I heard about using arrays but I'm not too sure on how to implement it in this context.
Thank you to anyone who reads this.
package com.example.textandviewbinding
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import android.widget.Toast
import com.example.textandviewbinding.databinding.ActivityMainBinding
import com.google.android.material.snackbar.Snackbar
import java.util.*
import kotlin.system.exitProcess
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
binding.btnSubmit.setOnClickListener {
validateUser(it)
}
}
private fun addTextView(text:String){
val textView1 = TextView(this)
textView1.text = text
textView1.textSize = 16f
textView1.textAlignment = View.TEXT_ALIGNMENT_CENTER
binding.myLayout.addView(textView1)
}
private fun validateUser(it: View) {
val username = binding.editUsername.text
val password = binding.editPassword.text
if (username.toString().equals("joed", ignoreCase = true) && password.toString().equals("1234")) {
// Toast.makeText(this, "Logged In!", Toast.LENGTH_SHORT).show()
val message = getString(R.string.welcome_message,username)
Snackbar.make(it, message, Snackbar.LENGTH_LONG)
.setAction("Show details.. ", { addTextView("Login Successful: ${Calendar.getInstance().time}" ) })
.show()
} else {
Toast.makeText(this, "Invalid Details", Toast.LENGTH_SHORT).show()
exitProcess(-1)
}
}
private fun displayToast() {
Toast.makeText(this, "Login Successful ${Calendar.getInstance().time}", Toast.LENGTH_SHORT).show()
}
}
1- Create a class called User , ex:
data class User(
var id : Int
var name : String
)
2- Create an Array of users using the User model in your MainActivity :
private val users = ArrayList<User>()
3- Add users to the array :
users.add(User(1,"Alex"))
users.add(User(2,"Andrei"))

Firebase connection create user error on Kotlin

ı try a create user on firebase with kotlin. but i get the error toast all the time
Theese are my imports:
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.Toast
import com.google.firebase.auth.FirebaseAuth
import kotlinx.android.synthetic.main.activity_create_user.*
here the rest of my code
class createUser : AppCompatActivity() {
private var fbsignup: FirebaseAuth = FirebaseAuth.getInstance()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_create_user)
submitButton.setOnClickListener {
val email = userSaveText.text.toString().trim()
val password = passSaveText.text.toString().trim()
if (TextUtils.isEmpty(email)) {
Toast.makeText(this, "enter a mail ", Toast.LENGTH_SHORT).show()
return#setOnClickListener
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(this, "enter password", Toast.LENGTH_SHORT).show()
return#setOnClickListener
}
fbsignup.createUserWithEmailAndPassword(email, password).addOnCompleteListener { task ->
if (task.isSuccessful) {
Toast.makeText(this, "succesfully created account", Toast.LENGTH_SHORT).show()
return#addOnCompleteListener
} else {
Toast.makeText(this, "errore!!", Toast.LENGTH_SHORT).show()
return#addOnCompleteListener
}
}}
}
What am i supposed to do?
Try to remove return #setOnClickListener and return
#addOnCompleteListener from if statements
try to initiate firebaseAuth like this:
private lateinit var fbsignup:FirebaseAuth
(before on create method)
And after on create method like this:
fbsignup=FirebaseAuth.getInstance()

Categories

Resources