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)
}
}
Related
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) {
}
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
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()
}
}
private fun logInRegisteredUser() {
if (validateLoginDetails()) {
// Show the progress dialog.
showProgressDialog(resources.getString(R.string.please_wait))
// Get the text from editText and trim the space
val email = et_email.text.toString().trim { it <= ' ' }
val password = et_password.text.toString().trim { it <= ' ' }
// Log-In using FirebaseAuth
FirebaseAuth.getInstance().signInWithEmailAndPassword(email, password)
.addOnCompleteListener { task ->
// Hide the progress dialog
hideProgressDialog()
if (task.isSuccessful) {
val currrentUser= FirebaseAuth.getInstance().currentUser
/* if (currrentUser != null) {
val washingtonre = mFireStore.collection("use").document(currrentUser.uid)
washingtonre.get().addOnSuccessListener(object: OnSuccessListener<DocumentSnapshot> {
override fun onSuccess(documentSnapshot:DocumentSnapshot) {
if (documentSnapshot.exists())
{
var arrList = ArrayList<String>()
arrList = documentSnapshot.get("organization") as ArrayList<String>
Toast.makeText(applicationContext,"$arrList",Toast.LENGTH_SHORT).show()
for (i in 0 until arrList.size)
{
//Traversing the list
}
}
}
})
}*/
if (currrentUser != null) {
val c = FirebaseFirestore.getInstance()
val d = c.collection("users").document(currrentUser.uid)
d.get().addOnSuccessListener { document ->
if (document != null) {
arrList = document.get("organization") as ArrayList<String>
if (arrList.size>1) {
val intent = Intent(this#LoginActivity, companyDetails::class.java)
intent.putStringArrayListExtra("key", arrList)
startActivity(intent)
Toast.makeText(applicationContext, "$arrList", Toast.LENGTH_SHORT).show()
}
else if (arrList.size<=1) {
val intent = Intent(this#LoginActivity, MainActivity::class.java)
startActivity(intent)
}
} else {
Log.d("Tag", "No such document")
}
}
.addOnFailureListener { exception ->
Log.d("TAG", "get failed with ", exception)
}
}
} else {
showErrorSnackBar(task.exception!!.message.toString(), true)
}
}
}
}
This is my code to validate login details. When login button is pressed this code is executed.
Now I want to check an array field named 'organization' in firestore to check wheather the user has two or more companies to his credits. Now when I run the app if organization field doesnt exist my app crashes. I want the app to work even if the organization field doesnt exist. How to change the codes for that?enter image description here
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.