how to get data from object _field in firestore - android

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.

Related

Read data from Firestore Jetpack Compose

I am currently trying to read data from Cloud Firestore, but while doing this I get this error message:
For-loop range must have an 'iterator()' method
And I don't know what to do to get rid of it. Maybe there is an easy way to fix this I haven't thought of yet...
I have been using this google firebase tutorial but with no success.
The error message comes on the documents in the for (document in documents) part of the code
The code I am using is this:
`
fun Varer() {
var firestore: FirebaseFirestore = FirebaseFirestore.getInstance()
var docRef = firestore.collection("varer").document("varer")
var source = Source.DEFAULT
docRef.get(source).addOnSuccessListener { documents ->
for (document in documents) {
Log.d(TAG, "${document.id} => ${document.data}")
var v1 = VareFB(
tittel = document["tittel"].toString(),
pris = document.getDouble("pris"),
beskrivelse = document["beskrivelse"].toString(),
bildeID = document["bildeID"].toString(),
)
varerListe.add(v1)
Log.d(TAG, document["tittel"].toString())
Log.d(TAG, v1.toString())
}
}
.addOnFailureListener { exception ->
Log.w(TAG, "Feil med henting av varer: ", exception)
}
}
`
data class VareFB (
val tittel: String,
val pris: Double?,
val beskrivelse: String,
val bildeID: String,
) {
#Exclude
fun toMap(): Map<String, Any?> {
return mapOf(
"tittel" to tittel,
"pris" to pris,
"beskrivelse" to beskrivelse,
"bildeID" to bildeID,
)
}
}
`
object VarerObject {
var varerListe = mutableListOf<VareFB>()
}
`
Edit:
fun Varer() {
var firestore: FirebaseFirestore = FirebaseFirestore.getInstance()
var docRef = firestore.collection("varer").document("varer")
var source = Source.DEFAULT
docRef.get(source).addOnSuccessListener { snapshot ->
for (document in snapshot.documents) {
Log.d(TAG, "${document.id} => ${document.data}")
var v1 = VareFB(
tittel = document["tittel"].toString(),
pris = document.getDouble("pris"),
beskrivelse = document["beskrivelse"].toString(),
bildeID = document["bildeID"].toString(),
)
varerListe.add(v1)
Log.d(TAG, document["tittel"].toString())
Log.d(TAG, v1.toString())
}
}
.addOnFailureListener { exception ->
Log.w(TAG, "Feil med henting av varer: ", exception)
}
}
documents is a QuerySnapshot object so there is no way you can iterate over it. To be able to iterate through the documents, you have to get the documents out of the QuerySnapshot object like this:
firestore.collection("varer").get(source).addOnSuccessListener { documents ->
for (document in documents.documents) {
//
}
}
But in my opinion, it's a little confusing. So I would rather name the object that comes from the lambda expression snapshot:
// 👇
firestore.collection("varer").get(source).addOnSuccessListener { snapshot ->
for (document in snapshot.documents) {
// 👆
}
}

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.

Firestore Database model create with kotlin

I'm trying to model a database schema for Firestore. How can I create this database model?
This is my recipe data class
data class Foods(
var foodId:String?,
var foodName:String,
var foodCategory:String,
var foodCalory:Int,
var foodIngredients:String,
var foodRecipe:String,
var foodCookingTime:Int,
var foodImg:String?)
My Users Id getting this
val user : FirebaseUser? = auth?.currentUser
val userID: String = user?.uid.toString()
As I see in your screenshot, your document (vp0q ...) holds an array of Foods objects. If you want to be able to map that document to an object of a particular class, you should consider using the following class declarations:
data class User (recipe: Array<Foods>)
Now, to read that document, you should use the following reference:
val uid = FirebaseAuth.getInstance().currentUser?.uid
val rootRef = FirebaseFirestore.getInstance()
val usersRef = rootRef.collection("users")
usersRef.document(uid).get()
.addOnSuccessListener { document ->
if (document != null) {
val recipe = document.toObject<Foods>().recipe
//Do what you need to do with your recipe array
} else {
Log.d(TAG, "No such document")
}
}
.addOnFailureListener { exception ->
Log.d(TAG, "get failed with ", exception)
}

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

How can I store document field data from a particular collection in firestore database to a string variable in kotlin

I want to get data from the cloud firestore and have to store it to a string variable but unable to do so and need help.
This is below code
val db = FirebaseFirestore.getInstance()
val docRef = db.collection("SlideShowImages").document("1")
docRef.get()
.addOnSuccessListener { document ->
if (document != null) {
Log.d(TAG, "DocumentSnapshot data: ${document.data}")
} else {
Log.d(TAG, "No such document")
}
}
.addOnFailureListener { exception ->
Log.d(TAG, "get failed with ", exception)
}
getting this from database and I want Link to store to variable first_image
{about=FCB, link=https://firebasestorage.googleapis.com/v0/b/missionx-g6305.appspot.com/o/EVENTS%2FSlide%20Show%20Images%2FCurrent%2FFCB.jpg?alt=media&token=950c5200-c553-4639-b33e-2b91a220b19c}
And I want to store it in variable
val first_image : String
first_image = document.data.link
when I use this I am getting an error
and put the variable type var so you can modify value. Val only allowed to set value permenant to that variable.
private var first_image: String
and get image in your variable :
first_image = document.getString("link");
Read Difference between val and var.

Categories

Resources