Unit Testing with Mockito & Firebase Kotlin - android

I am trying to write a unit tests to my kotlin class that writes and reads values from Firebase. I tried in different ways of writing the tests but always got errors with firebase.
This is my Repository Class:
package mainPackage.model
import com.google.firebase.firestore.FirebaseFirestore
import android.util.Log
import com.google.firebase.firestore.FirebaseFirestoreException
import mainPackage.utils.Checks
const val TAG = "FIRESTORE"
class RepositoryMockup {
//--------------------------------
//Firebase functions
fun writeNewUser(pass: String, email: String, isATeacher: Boolean?) {
val database = FirebaseFirestore.getInstance()
val myRef = database.collection("Users").document(email)
val newUser = hashMapOf(
"is_a_teacher" to isATeacher,
"pass" to pass
)
myRef.set(newUser)
.addOnSuccessListener { Log.d(TAG, "User successfully added") }
.addOnFailureListener { e -> Log.w(TAG, "Error writing user", e) }
}
//CHECKED AND FIXED
fun userLogin(user: User, callback: (Checks) -> Unit) {
val database = FirebaseFirestore.getInstance()
val myRef = database.collection("Users").document(user.email.toString())
myRef.get()
.addOnSuccessListener { document ->
if (document != null && document.exists()) {
val pass = document.get("pass") as String
if (pass == user.password) {
callback(Checks.PASSED)
} else {
callback(Checks.FAILED_CHECK)
}
Log.d(TAG, "Pass successfully checked")
} else {
callback(Checks.NEW_USER_CREATED)
Log.d(TAG, "Is empty")
writeNewUser(user.password.toString(), user.email.toString(), user.isATeacher)
}
}
.addOnFailureListener { exception ->
if (exception is FirebaseFirestoreException) {
Log.e(TAG, "Error getting document: ", exception)
}
callback(Checks.FAILED_CHECK)
}
}
fun userLoginTest(user: UserTest, callback: (Checks) -> Unit) {
val database = FirebaseFirestore.getInstance()
val myRef = database.collection("Users").document(user.email.toString())
myRef.get()
.addOnSuccessListener { document ->
if (document != null && document.exists()) {
val pass = document.get("pass") as String
if (pass == user.pass) {
callback(Checks.PASSED)
} else {
callback(Checks.FAILED_CHECK)
}
Log.d(TAG, "Pass successfully checked")
} else {
callback(Checks.NEW_USER_CREATED)
Log.d(TAG, "Is empty")
writeNewUser(user.pass.toString(), user.email.toString(), user.isATeacher)
}
}
.addOnFailureListener { exception ->
if (exception is FirebaseFirestoreException) {
Log.e(TAG, "Error getting document: ", exception)
}
callback(Checks.FAILED_CHECK)
}
}
//CHECKED AND FIXED
fun readNameSurnameByEmail(email: String, callback: (String) -> Unit){
val database = FirebaseFirestore.getInstance()
val myRef = database.collection("Users").document(email)
myRef.get()
.addOnSuccessListener { document ->
if (document != null) {
val fieldValue = document.get("name_surname") as String
callback(fieldValue)
Log.d(TAG, "Name and surname successfully read")
} else {
Log.d(TAG, "Is empty")
}
}
.addOnFailureListener { exception ->
if (exception is FirebaseFirestoreException) {
Log.e(TAG, "Error getting document: ", exception)
}
}
}
//CHECKED
fun readIsATeacherByEmail(email: String): Boolean {
val database = FirebaseFirestore.getInstance()
val myRef = database.collection("Users").document(email)
var fieldValue = false
myRef.get()
.addOnSuccessListener { document ->
if (document != null) {
fieldValue = document.get("is_a_teacher") as Boolean
Log.d(TAG, "Name and surname successfully read")
} else {
Log.d(TAG, "Is empty")
}
}
.addOnFailureListener { exception ->
if (exception is FirebaseFirestoreException) {
Log.e(TAG, "Error getting document: ", exception)
}
}
return fieldValue
}
//CHECKED
fun writeOfficeHoursInstance(email: String, timeFrom: String, timeTo: String) {
val database = FirebaseFirestore.getInstance()
var id = ""
val myRef = database.collection("OfficeHoursInstance").document()
id = myRef.id
val newInstance = hashMapOf(
"email" to email,
"time_from" to timeFrom,
"time_to" to timeTo,
"id" to id
)
myRef.set(newInstance)
.addOnSuccessListener { Log.d(TAG, "Instance successfully added") }
.addOnFailureListener { e -> Log.w(TAG, "Error writing Instance", e) }
}
//CHECKED AND FIXED
fun readOfficeHoursInstanceTeacher(email: String, callback: (MutableList<OfficeHoursInstance>) -> Unit){
var timeFrom = ""
var timeTo = ""
var userEmail = ""
var code = ""
var list = mutableListOf<OfficeHoursInstance>()
val database = FirebaseFirestore.getInstance()
val ref = database.collection("OfficeHoursInstance")
.whereEqualTo("email", email)
ref.get()
.addOnSuccessListener { documents ->
for (document in documents) {
timeFrom = document.get("time_from") as String
timeTo = document.get("time_to") as String
userEmail = document.get("email") as String
code = document.get("id") as String
list.add(OfficeHoursInstance(userEmail, timeFrom, timeTo, code))
Log.d(TAG, " Time instance successfully read")
}
callback(list)
}
.addOnFailureListener { exception ->
if (exception is FirebaseFirestoreException) {
Log.e(TAG, "Error getting document: ", exception)
}
}
}
fun updateUserOfficeHoursList(email: String, code: String){
val database = FirebaseFirestore.getInstance()
val ref = database.collection("Users").document(email)
var list = ""
ref.get()
.addOnSuccessListener { document ->
if (document != null) {
list = document.get("office_hours_list") as String
Log.d(TAG, "office_hours_list successfully read")
} else {
Log.d(TAG, "Is empty")
}
}
.addOnFailureListener { exception ->
if (exception is FirebaseFirestoreException) {
Log.e(TAG, "Error getting document: ", exception)
}
}
if (list.isEmpty()){
list = code
}
else {
list + ", " + code
}
ref.update("office_hours_list", list)
}
}
Can you give me a clue how to write a unit test for my db methods?
Or show me the structure?
Here is what I have but it is not working:
package mainPackage.tests
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.DocumentSnapshot
import com.google.firebase.firestore.FirebaseFirestoreException
import mainPackage.model.RepositoryMockup
import mainPackage.model.UserTest
import mainPackage.utils.Checks
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.MockitoAnnotations
class RepositoryMockupTest {
private lateinit var repositoryMockup: RepositoryMockup
#Mock
private lateinit var firebaseFirestore: FirebaseFirestore
#Mock
private lateinit var documentSnapshot: DocumentSnapshot
#Before
fun setUp() {
MockitoAnnotations.initMocks(this)
repositoryMockup = RepositoryMockup()
}
#Test
fun testWriteNewUser() {
repositoryMockup.writeNewUser("password", "email", true)
Mockito.verify(firebaseFirestore).collection("Users").document("email")
}
#Test
fun testUserLogin_Passed() {
val user = UserTest("man.man#pwr.edu.pl", "password123", true)
Mockito.`when`(firebaseFirestore.collection("Users").document("email").get())
.thenReturn(documentSnapshot)
Mockito.`when`(documentSnapshot.exists()).thenReturn(true)
Mockito.`when`(documentSnapshot.get("pass")).thenReturn("password")
var check = Checks.FAILED_CHECK
repositoryMockup.userLoginTest(user) {
check = it
}
assertEquals(Checks.PASSED, check)
}
#Test
fun testUserLogin_FailedCheck() {
val user = UserTest("man.man#pwr.edu.pl", "wrong_password", true)
Mockito.`when`(firebaseFirestore.collection("Users").document("user.email").get())
.thenReturn(documentSnapshot)
Mockito.`when`(documentSnapshot.exists()).thenReturn(true)
Mockito.`when`(documentSnapshot.get("pass")).thenReturn("password")
var check = Checks.PASSED
repositoryMockup.userLoginTest(user) {
check = it
}
assertEquals(Checks.FAILED_CHECK, check)
}
// #Test
// fun testUserLogin_NewUserCreated() {
// val user = UserTest("email", "password", true)
// Mockito.`when`(firebaseFirestore.collection("Users").document("user.email").get())
// .thenReturn(documentSnapshot)
// Mockito.`when`(documentSnapshot.exists()).thenReturn(false)
// var check = Checks.PASSED
// repositoryMockup.userLoginTest(user) {
// check = it
// }
// assertEquals(Checks.NEW_USER_CREATED, check)
// }
}
private fun Any.thenReturn(documentSnapshot: DocumentSnapshot) {
}

Related

How to insert a node with a value, depending on whether it exists or not

I am making a user registration with Authentication, but in turn, I insert these registrations in a collection of Firebase Realtime Database.
The structure of the database is as follows:
viewmodel of my register screen:
class RegisterViewModel : ViewModel() {
var email = mutableStateOf("")
var userName = mutableStateOf("")
var password = mutableStateOf("")
var status = mutableStateOf("1")
val state = mutableStateOf(RegisterState())
val user = FirebaseAuth.getInstance().currentUser
val loginPresenter = AuthPresenter()
fun registrar(email: String, password: String) {
viewModelScope.launch {
state.value = state.value.copy(isLoading = true)
if (
Common.isValidString(email.trim()) &&
Common.isValidPassword(password.trim()) &&
Common.isValidName(userName.value.trim()) &&
Common.isValidStatus(status.value)
) {
loginPresenter.signUp(email.trim(), password).addOnSuccessListener {
try {
val empleado = Empleado(
it.user!!.uid,
userName.value.trim(),
it.user!!.email!!,
status.value,
)
loginPresenter.createUserInDb(empleado).addOnSuccessListener {
state.value = state.value.copy(isSuccess = true)
}.addOnFailureListener { exception ->
state.value = state.value.copy(isError = exception.message)
}
} catch (e: Exception) {
state.value = state.value.copy(isError = e.message)
}
}.addOnFailureListener {
state.value = state.value.copy(isLoading = false)
state.value = state.value.copy(isError = it.message)
}
} else {
state.value = state.value.copy(isLoading = false)
state.value = state.value.copy(isError = "Rellena bien los campos")
}
}
}
fun dismiss() {
state.value = state.value.copy(isError = null)
}
And here the calls:
override suspend fun signUp(email: String, password: String): Task<AuthResult> {
return mAuth.createUserWithEmailAndPassword(email, password)
}
override fun createUserInDb(user: Empleado): Task<Void> {
return usersRef.child(user.uid!!).setValue(user.toMap())
}
First of all, the collection is: "employees"
and the document fields are:
.uid
.userName
.e-mail
.status
What I want to do is the following;
If there is no document in the "employees" collection;
The status field of the document to be inserted takes a value of 38. But if a document already exists in the collection, it takes the value of 1

Firestore DocumentReference type to object

As you can see in the picture, the documents in the person collection refer to the statistics collection.
I can pull this data like this
PersonRepository
override fun getPersonsFromFirestore(): Flow<Response<List<Person>>> = callbackFlow {
val snapshotListener =
personsCollection.addSnapshotListener { snapshot, e ->
val response = if (snapshot != null) {
val personList = snapshot.toObjects(Person::class.java)
Response.Success(personList)
} else {
throw Error(e?.message ?: e.toString())
}
trySend(response).isSuccess
}
awaitClose {
snapshotListener.remove()
}
}
Model
data class Person(
val id: Int=0,
val name: String="",
val surname: String="",
val image_url: String="",
val biography: String="",
val team: String="",
val statistics: DocumentReference? = null,
var personStatistics: PersonStatistics? = null
)
How can I convert Document Reference to object here?
I tried this first
override fun getPersonsFromFirestore(): Flow<Response<List<Person>>> = callbackFlow {
val snapshotListener =
personsCollection.addSnapshotListener { snapshot, e ->
val response = if (snapshot != null) {
val personList = mutableStateListOf<Person>()
snapshot.onEach {
val person = it.toObject(Person::class.java)
person.statistics!!.get().addOnSuccessListener {
val personStatistics = it.toObject(PersonStatistics::class.java)
person.personStatistics = personStatistics
}
personList.add(person)
}
//val personList = snapshot.toObjects(Person::class.java)
Response.Success(personList)
} else {
throw Error(e?.message ?: e.toString())
}
trySend(response).isSuccess
}
awaitClose {
snapshotListener.remove()
}
}
but in this approach Person Statistics comes first as null. It is added later. How can I bring them all at once? Or is there another better way?
Okey, This is how I solved it,
override fun getPersonsFromFirestore(): Flow<Response<List<Person>>> = callbackFlow {
val snapshotListener =
personsCollection.addSnapshotListener { snapshot, e ->
val response = if (snapshot != null) {
val personList = mutableStateListOf<Person>()
snapshot.onEach {
val person = it.toObject(Person::class.java)
val statistics = it.data["statistics"] as DocumentReference
statistics.addSnapshotListener { value, error ->
if (value!=null){
person.personStatistics = value.toObject(PersonStatistics::class.java)
personList.add(person)
}else{
throw Error(error?.message ?: error.toString())
}
}
}
Response.Success(personList)
} else {
throw Error(e?.message ?: e.toString())
}
trySend(response).isSuccess
}
awaitClose {
snapshotListener.remove()
}
}

Upload and show data Firestore kotlin

I have a problem whit my code, but I get no errors. The problem arise when I try change my variables ”artistName” and ”trackName” to my object ”SoundTrack”. If I use my variables ”artistName” and ”trackName” it works fine, I can upload, delete and display data etc. But when I try o use my object nothing is happend, It’s like it doesn’t connect to my database.
My class:
class SoundTrack (val name : String, val track : String)
Here is my MainActivity:
class MainActivity : AppCompatActivity(), View.OnClickListener {
val collection = "song"
//val artistName = "name"
//val trackName = "track"
var docId =""
lateinit var newTrack : SoundTrack
lateinit var db : FirebaseFirestore
lateinit var alSongs : ArrayList<HashMap<String,Any>>
lateinit var adapter: SimpleAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
alSongs = ArrayList()
addData.setOnClickListener(this)
updateInfo.setOnClickListener(this)
deleteInfo.setOnClickListener(this)
IsData.setOnItemClickListener(itemClick)
}
override fun onStart() {
super.onStart()
db = FirebaseFirestore.getInstance()
db.collection(collection).addSnapshotListener { querySnapshot, e ->
if(e != null) Log.d("fireStore", e.message)
showData()
}
}
//add new data by input
override fun onClick(v: View?) {
when(v?.id){
R.id.addData ->{
println("hej")
if(::newTrack.isInitialized){
val hm = HashMap<String, Any>()
hm.set(newTrack.name,artistNametxt.text.toString())
hm.set(newTrack.track,trackNametxt.text.toString())
db.collection(collection).document(artistNametxt.text.toString()).set(hm).
addOnSuccessListener {
Toast.makeText(this, "Data Successfully added", Toast.LENGTH_SHORT)
.show()
}.addOnFailureListener { e ->
Toast.makeText(this, "Data unSuccessfully added : ${e.message}", Toast.LENGTH_SHORT)
.show()
}
}
}
//Update input
R.id.updateInfo -> {
if(::newTrack.isInitialized){
val hm = HashMap<String, Any>()
hm.set(newTrack.name,artistNametxt.text.toString())
hm.set(newTrack.track,trackNametxt.text.toString())
db.collection(collection).document(docId).update(hm)
.addOnSuccessListener { Toast.makeText(this, "Data Successfully updated", Toast.LENGTH_SHORT)
.show() }
.addOnFailureListener { e ->
Toast.makeText(this, "Data unSuccessfully updated : ${e.message}", Toast.LENGTH_SHORT)
.show()
}
}
}
//delete Input
R.id.deleteInfo -> {
if(::newTrack.isInitialized){
db.collection(collection).whereEqualTo(newTrack.name,docId).get().addOnSuccessListener {
results ->
for(doc in results){
db.collection(collection).document(doc.id).delete()
.addOnSuccessListener {
Toast.makeText(this, "Data Successfully updated", Toast.LENGTH_SHORT)
.show()
}.addOnFailureListener { e ->
Toast.makeText(this, "Data unSuccessfully updated : ${e.message}", Toast.LENGTH_SHORT)
.show()
}
}
}.addOnFailureListener { e ->
Toast.makeText(this, "Cant get data reference: ${e.message}", Toast.LENGTH_SHORT)
.show()
}
}
}
}
}
val itemClick = AdapterView.OnItemClickListener { parent, view, position, id ->
val hm = alSongs.get(position)
docId = hm.get(newTrack.name).toString()
artistNametxt.setText(hm.get(newTrack.name).toString())
trackNametxt.setText(hm.get(newTrack.name).toString())
}
//Show input data
fun showData(){
if(::newTrack.isInitialized){
db.collection(collection).get().addOnSuccessListener { result ->
alSongs.clear()
for(doc in result){
val hm = HashMap<String,Any>()
hm.set(newTrack.name,doc.get(newTrack.name).toString())
hm.set(newTrack.track,doc.get(newTrack.track).toString())
alSongs.add(hm)
}
}
adapter = SimpleAdapter(this,alSongs,R.layout.row_data,
arrayOf(newTrack.name,newTrack.track),
intArrayOf(R.id.txName, R.id.TxTrack))
IsData.adapter = adapter
}
}
}
Try this
fun getSongs(): LiveData<MutableList<SongTrack>> {
firestoreInstance.collection(SONG_COLLECTION)
.addSnapshotListener { querySnapshot,
firebaseFirestoreException ->
song.clear()
querySnapshot?.documents?.forEach {document ->
val songTrack = document.toObject(SongTrack::class.java)
songTrack?.let {
song.add(it)
}
}
}
songList.postValue(song)
return songList
}
First i would change
class SoundTrack (val name : String, val track : String)
to
data class SoundTrack(val name : String ="",val track : String ="")
and delete
lateinit var newTrack : SoundTrack
so you don't need to do this anymore
if(::newTrack.isInitialized)
delete
lateinit var db : FirebaseFirestore
and create Object class
object FirestoreUtil {
private val firestoreInstance: FirebaseFirestore by lazy {
FirebaseFirestore.getInstance()
}
}
or better yet
class MainActivity : AppCompatActivity() {
lateinit var adapter: SimpleAdapter
val itemClick = AdapterView.OnItemClickListener { parent, view, position, id ->
val selectedSong = FirestoreUtils.songList.value?.get(position)
selectedSong?.let {
artistNametxt.setText(it.name.toString())
trackNametxt.setText(it.track.toString())
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
FirestoreUtils.getSongs().observe(this, Observer { songList ->
adapter = SimpleAdapter(
this, songList, R.layout.row_data,
arrayOf(SongTrack().name, SongTrack().track),
intArrayOf(R.id.txName, R.id.TxTrack)
)
IsData.adapter = adapter
})
addData.setOnClickListener {
FirestoreUtils.addSong(
SongTrack(
artistNametxt.text.toString(),
trackNametxt.text.toString()
)
) { message -> Toast.makeText(this, message, Toast.LENGTH_SHORT).show() }
}
updateInfo.setOnClickListener {
FirestoreUtils.updateSong(
SongTrack(
artistNametxt.text.toString(),
trackNametxt.text.toString()
)
) { message ->
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
}
deleteInfo.setOnClickListener(FirestoreUtils.deleteSong(artistNametxt.text.toString()) { message ->
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
})
IsData.setOnItemClickListener {
itemClick
}
}
}
const val SONG_COLLECTION = "song"
data class SongTrack(val name: String = "", val track: String = "")
object FirestoreUtils {
private val firestoreInstance: FirebaseFirestore by lazy {
FirebaseFirestore.getInstance()
}
private val songCollection = firestoreInstance.collection(SONG_COLLECTION)
private val song = mutableListOf<SongTrack>()
val songList: MutableLiveData<MutableList<SongTrack>> = MutableLiveData()
fun getSongs(): LiveData<MutableList<SongTrack>> {
firestoreInstance.collection(SONG_COLLECTION)
.addSnapshotListener { querySnapshot,
firebaseFirestoreException ->
song.clear()
querySnapshot?.documents?.forEach {
it.toObject<SongTrack>()?.let { songTrack ->
song.add(songTrack)
}
}
}
songList.postValue(song)
return songList
}
fun addSong(songTrack: SongTrack, onComplete: (String) -> Unit) {
songCollection.document(songTrack.name)
.set(songTrack)
.addOnSuccessListener { onComplete("Data Successfully added") }
.addOnFailureListener { onComplete("Data unSuccessfully added : ${it.message}") }
}
fun updateSong(songTrack: SongTrack, onComplete: (String) -> Unit) {
songCollection.document(songTrack.name)
.set(songTrack)
.addOnSuccessListener { onComplete("Data Successfully updated") }
.addOnFailureListener { onComplete("Data unSuccessfully updated : ${it.message}") }
}
fun deleteSong(songTrack: SongTrack, onComplete: (String) -> Unit) {
val deleteSong = songTrack.name
songCollection.document(songTrack.name).delete()
.addOnSuccessListener { onComplete("Song $deleteSong deleted") }
.addOnFailureListener { onComplete("Not found the song id : ${songTrack.name}") }
}
}
I just edit from your code, Did not test yet!!!
Enjoy.

how can i paginate data in kotlin using firestore?

I have created adapter which is fetching data from firestore.
But I need to paginate it in kotlin, can you help me?
private fun fetch(){
try {
mShared = getSharedPreferences("mShared", 0)
val path = mShared!!.getString("governorate", "Suez").toString()
dp!!.collection("Fraise")
.whereEqualTo("governorate", "${path}")
.orderBy("time")
.limit(5)
.get()
.addOnCompleteListener {
data.addAll(it.result.toObjects(Data::class.java))
adapter = Fraise_adapter(this, data)
adapter.notifyDataSetChanged()
recyclerView.adapter = adapter
}
} catch (e: Exception) {
Toast.makeText(this, "Please choose a governorate from the main activity", Toast.LENGTH_LONG).show()
}
}
This works for me. For Firestore pagination.
private fun first(){
val first = collectionRef
.orderBy("priority")
.limit(3)
first.get()
.addOnSuccessListener {
var lastVisible = it.documents[it.size()-1]
var text = ""
for (document in it) {
val note = document.toObject(Note::class.java)
note.noteId = document.id
text+= note.title+"\n"
}
binding.tvShow.append(text)
binding.btnShow.setOnClickListener {
val next = collectionRef
.orderBy("priority")
.startAfter(lastVisible)
.limit(3)
next.get()
.addOnSuccessListener {
var text = ""
for (document in it) {
val note = document.toObject(Note::class.java)
note.noteId = document.id
text+= note.title+"\n"
}
if(it.size()>0) {
text += "--------------------------\n\n"
binding.tvShow.append(text)
lastVisible = it.documents[it.size()-1]
}
}
}
}
.addOnFailureListener {
Toast.makeText(this, "Failed", Toast.LENGTH_SHORT).show()
Log.d(TAG, it.message)
}
}

Facebook info not showing

I'm trying to get the user info with this code but is not showing on the activity
The profile picture and the name are not creating a new user on the base
What am I missing?
Does anyone had coded this using Kotlin?
private fun handleFacebookAccessToken(token: AccessToken) {
Log.d(TAG, "handleFacebookAccessToken:" + token)
val credential = FacebookAuthProvider.getCredential(token.token)
App.currentAuth.signInWithCredential(credential)
.addOnCompleteListener(this) { Log.d(TAG, "signInWithCredential:success") }
.addOnSuccessListener(this) { authResult ->
if (authResult != null) {
val firebaseUser = authResult.user
if (App.database_table_users.child(firebaseUser.uid) == null) {
var facebookId = ""
firebaseUser.providerData
.filter { it.providerId == FacebookAuthProvider.PROVIDER_ID }
.forEach { facebookId = it.uid }
val photoUrl = "https://graph.facebook.com/$facebookId/picture?width=1024&height=1024"
App.database_table_users.child(firebaseUser.uid).setValue(
User(firebaseUser.uid,
firebaseUser.email.orEmpty(),
firebaseUser.displayName.orEmpty(),
photoUrl,
false
)
)
}
}
}
.addOnFailureListener(this) { ex ->
if (ex is FirebaseAuthUserCollisionException) {
LoginManager.getInstance().logOut()
val ad = AlertDialog.Builder(this#LoginActivity)
ad.setMessage(getString(R.string.auth_user_collision))
ad.setPositiveButton(getString(R.string.ok), null)
ad.show()
} else {
ex.printStackTrace()
}
}
}
You must use FirebaseAuth.getInstance() instead of App.currentAuth.
For example;
val mAuth = FirebaseAuth.getInstance()
val credential = FacebookAuthProvider.getCredential(token)
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
val user = mAuth.currentUser
} else {
task.exception?.printStackTrace()
}
}
Try This it's work for me
private fun loginWithFaceBook()
{
LoginManager.getInstance().registerCallback(callbackManager, facebookCallBack)
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile","email"))
}
private val facebookCallBack = object : FacebookCallback<LoginResult> {
override fun onSuccess(result: LoginResult?) {
val graphRequest = GraphRequest.newMeRequest(result?.accessToken) { _, response ->
val graphObject = response.jsonObject
val id = if(graphObject.has("id")) graphObject.getString("id") else null
val email = if(graphObject.has("email")) graphObject.getString("email") else null
val firstName = if(graphObject.has("first_name")) graphObject.getString("first_name") else null
val lastName = if(graphObject.has("last_name")) graphObject.getString("last_name") else null
val photoUrl = if(graphObject.has("picture")) {
val picture : JSONObject = graphObject.getJSONObject("picture")
if(picture.has("data") && picture.has("url") && picture.getString("url").isNotBlank()) {
picture.getString("url")
}
else
null
}
else
val bundle = Bundle()
bundle.putString("fields", "id,first_name,last_name,name,picture,email,gender,birthday,link")
graphRequest.parameters = bundle
graphRequest.executeAsync()
}
override fun onError(error: FacebookException) {
when{
error.message != null -> showSnackbar(error.message.toString())
}
}
override fun onCancel() {
}
}

Categories

Resources