How to get array data from Firestore? Android Kotlin - android

I have an array in Firestore. How can I get array items? I need streamers array type of string.
What I try is:
firebaseFireStore.collection("Agencies")
.addSnapshotListener { snapshot, e ->
if (e == null) {
val documents = snapshot?.documents
if(documents != null) {
val list = mutableListOf<Ajanslar>()
for (document in documents) {
val agencyName = document.get("agencyName").toString()
val coverImage = document.get("coverImage").toString()
val owner = document.get("owner").toString()
val platform = document.get("platform").toString()
val streamers = document.get("streamers")
val newAjans = Ajanslar(agencyName,coverImage,owner,platform,streamers)
list.add(newAjans)
}
ajansListRepo.value = list
}
}
}
Streamers give error and says Type mismatch. Required: kotlin.collections.ArrayList<String> /* = java.util.ArrayList<String> */ Found: Any?
My firestore is like that:
I found an answer like that in Java but I couldn't do it.
rootRef.collection("products").document("06cRbnkO1yqyzOyKP570").get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
ArrayList<String> list = (ArrayList<String>) document.get("ip_range");
Log.d(TAG, list.toString());
}
}
}
});

I wrote that answer and the solution is quite simple in Kotlin. As I see in your screenshot, the streamers field is an array of strings. When you call DocumentSnapshot#get(), the type of object that is returned is Any and not a List<String>. If you need that, you have to explicitly perform a cast to such an object. So please change the following line of code:
val streamers = document.get("streamers")
Into:
val streamers = document.get("streamers") as List<String>

Related

How to read and delete a document in firestore collection as one operation in kotlin

I have a firestore collection and I would like to read and delete a document as one operation in kotlin. I want to make sure no other user is able to read the same document before I delete it.
Here is my code in kotlin. CollRef is reference to the firestore collection. MY Collection contains simple documents with fields only.
I found online to use lock mechanism or firebase security rule but I don't know how to implement them.
private val db: FirebaseFirestore=FirebaseFirestore.getInstance()
private val collRef: CollectionReference = db.collection("Queue")
runBlocking {
val querySnapshot = collRef.limit(1).get()
.addOnSuccessListener { querySnapshot ->
if (!querySnapshot.isEmpty) {
val documentSnapshot = querySnapshot.documents[0]
if (documentSnapshot.data?.isNotEmpty()!!) {
db.runTransaction { transaction ->
val snapshot = transaction.get(documentSnapshot.reference)
if (snapshot.data?.isNotEmpty() == true) {
transaction.delete(documentSnapshot.reference)
}
// Success
null
}.addOnSuccessListener {
Utils.data["from"] = documentSnapshot.data!!["from"]
Utils.data["to"] = documentSnapshot.data!!["to"]
Utils.data["sender"] = documentSnapshot.data!!["sender"]
Utils.data["time"] = documentSnapshot.data!!["time"]
}
.addOnFailureListener { e ->
}
}
}
}
.addOnFailureListener {
}
}

Why can't I access my data from Firestore?

I'm trying to display data from Firestore and add it to a PieChart.
I can't figure out why I can't access my data
This is how data are stored in Firestore:
This is how I try to access it:
private val mFirestore = FirebaseFirestore.getInstance()
var chartdata: ArrayList<Measurements> = ArrayList()
private var chart: ScatterChart? = null
fun getCurrentUserID(): String {
val currentUser = FirebaseAuth.getInstance().currentUser
var currentUserID = ""
if (currentUser != null) {
currentUserID = currentUser.uid
}
return currentUserID
}
mFirestore.collection(Constants.MEASUREMENTS)
.whereEqualTo(Constants.USER_ID, getCurrentUserID())
.get()
.addOnSuccessListener { queryDocumentSnapshots ->
val userdata : ArrayList<Measurements> = ArrayList()
val weekdata = ArrayList<Measurements>()
if (!queryDocumentSnapshots.isEmpty) {
for (journals in queryDocumentSnapshots) {
val displayData: Measurements = journals.toObject(Measurements::class.java)
userdata.add(displayData)
Log.e("Data for chart", journals.toString())
}
And I get this error:
enter image description here
The data is being fetched precisely that's why you can see all the document names in the logcat but as you are logging DocumentSnapshot object, that's why you are seeing the data in unusual format. Try logging displayData variables like:
Log.d("Data for chart", displayData.activity) // Use Log.d instead of Log.e
or userdata as an array and it will work as desired.

How to get the keys in a Firestore document?

Hello, this is Kotlin Beginner.
While playing with Firestore, I suddenly had a question.
The value of a field can be easily retrieved, but
Is there a way to get the text of the field itself?
I would like to take the blue square in the following image literally.
Any help would be appreciated.
DocumentSnapshot#getData() method, returns an object of type Map<String!, Any!>. To get the keys of a document, simply iterate through the Map object, as explained in the following lines of code:
val uid = FirebaseAuth.getInstance().currentUser!!.uid
val rootRef = FirebaseFirestore.getInstance()
val uidRef = rootRef.collection("users").document(uid)
uidRef.get().addOnSuccessListener { document ->
if (document != null) {
document.data?.let { data ->
data.forEach { (key, _) ->
Log.d(TAG, key)
}
}
} else {
Log.d(TAG, "No such document")
}
}.addOnFailureListener { exception ->
Log.d(TAG, "get failed with ", exception)
}
To obtain the following result in the logcat:
email
id
nickname
password
phone

Iterate Values of a dataSnapshot.value hashmap from a Firebase

I'm creating a "Virtual Garage App" for motorcycles, and I can't retrieve the data from my Firebase, I can only access the HashMap of each motorcycle in database.
This is my database content:
database
Here is my code where I try to retrieve the data:
code
Here is the ExampleItem() object where I try to place the data: ExampleItem
Is there any way to iterate through the values of the dataSnapshot.value HashMap in order to call the setters for each string?
Is there any way to iterate through the values of the dataSnapshot.value HashMap in order to call the setters for each string?
You can get it even simpler, by accessing the exact property you need. For example, to display the value of "motoBrand" property, please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference mototrackRef = rootRef.child("mototrack");
mototrackRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
for (DataSnapshot ds : task.getResult().getChildren()) {
String motoBrand = ds.child("motoBrand").getValue(String.class);
Log.d("TAG", motoBrand);
}
} else {
Log.d("TAG", task.getException().getMessage()); //Don't ignore potential errors!
}
}
});
In the exact same way you can get the value of the other properties. In kotlin will look like this:
val rootRef = FirebaseDatabase.getInstance().reference
val mototrackRef = rootRef.child("mototrack")
mototrackRef.get().addOnCompleteListener { task ->
if (task.isSuccessful) {
for (ds in task.result.getChildren()) {
val motoBrand = ds.child("motoBrand").getValue(String::class.java)
Log.d("TAG", motoBrand)
}
} else {
Log.d("TAG", task.exception.getMessage()) //Don't ignore potential errors!
}
}

how to get data from object _field in firestore

i need to get data from object (named "0") in a document in firestore, is that possible ?
this is my code now:
val db = FirebaseFirestore.getInstance()
val docRef = db.collection("accessories")
.document("brand0")
docRef.get().addOnCompleteListener(OnCompleteListener<DocumentSnapshot> { task ->
if (task.isSuccessful) {
val document = task.result
val group = document.get("0") as ArrayList<String>
}
but casting Any to Arraylist is not possible, any other way to get these data ?
It looks like 0 is a an object type field. That means it'll be represented locally as a Map type object with strings as the keys for the properties it contains.
After some trials and errors this is what worked for me in the end, but I am not sure why. I am using kotlin in my current project.
fun getOwner(userId: String) {
val db = Firebase.firestore
val docRef = db.collection("users").document(userId)
docRef.get()
.addOnSuccessListener { document ->
if (document != null) {
Log.d(TAG, "DocumentSnapshot data: ${document.data}")
val data = document.data as Map<String, String>
showOwnerName.text = data["name"]
} else {
Log.d(TAG, "No such document")
}
}
.addOnFailureListener { exception ->
Log.d(TAG, "get failed with ", exception)
}
}
I am converting the data I am getting to a map and this is how I am able to access its values.

Categories

Resources