How i can read just color item in the image with out all data sub child?
I try this
val database = FirebaseDatabase.getInstance()
val personalDataReference = database.getReference("user personal data")
val messageList = ArrayList<String>()
personalDataReference.addValueEventListener(object : ValueEventListener{
override fun onDataChange(dataSnapshot: DataSnapshot){
messageList.add(dataSnapshot.value.toString())
}
override fun onCancelled(error: DatabaseError) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException())
}
})
but it get all the data
Consider using the Firebase Kotlin SDK by GitLive.
This library is also multi-platform, so the same code can be used on both Android and on iOS via Kotlin Multiplatform Mobile.
The code to read the keys from Firebase realtime database would look like this:
val keys = db.reference("/path/to/user personal data")
.valueEvents
.first()
.children
.mapNotNull { it.key }
Note here that valueEvents is a Kotlin Flow of DataSnapshot, therefore you can do more than simply taking the first snapshot and mapping it to a list as shown above. See the Flow documentation.
The things you've marked yellow are known as keys in Firebase terms.
To get a list of only the keys, you can do:
personalDataReference.addValueEventListener(object : ValueEventListener{
override fun onDataChange(dataSnapshot: DataSnapshot){
for (childSnapshot in dataSnapshot.children) {
messageList.add(childSnapshot.key)
}
}
Note that this will still read all JSON from the database, but the list will only contain the keys.
Related
I need to order items from firebase by timestamp. Then I would like to sum the total price so far I have managed to list the products inside a recyclerview, but they are not ordered
private fun getProductData(){
dref = FirebaseDatabase.getInstance().getReference("Products")
dref.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()){
for (productSnapshot in snapshot.children){
val product = productSnapshot.getValue(ProductData::class.java)
productList.add(product!!)
}
prodList.adapter = productAdapter
}
}
override fun onCancelled(error: DatabaseError) {
Toast.makeText(activity, error.message, Toast.LENGTH_SHORT).show()
}
})
if someone can help me order them, and if possible show me how to find the sum of the price. I have read many docs but they don't ring the bell.
To order the child nodes you'll want to use a query as shown in the documentation on ordering and filtering data:
dref = FirebaseDatabase.getInstance().getReference("Products")
val query = dref.orderByChild("prodTime")
query.addValueEventListener(object : ValueEventListener {
...
I am trying to fetch data from firebase based on userId, when the user logged in I need to show his profile details based on its id but I am unable to fetch it. Any help?
auth = FirebaseAuth.getInstance()
databaseRef = FirebaseDatabase.getInstance().getReference("Users/")
databaseRef.addValueEventListener(object: ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
//I want first_name and all other details of users
Log.e("first_name", snapshot.child(uid).getValue(String::class.java))
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
One problem is that you don't seem to initialize uid anywhere. So that should be:
auth = FirebaseAuth.getInstance()
uid = auth.currentUser.uid
Also see the Firebase documentation on getting the current user.
Next is not necessarily a bug, but definitely an optimization you'll want to do. Right now you read the entire Users node into your Android app, to then only get a value from /Users/$uid. As you add more users to the database, this is not going to scale.
What you'll want to do instead, is only load the node for the current user from the database with:
databaseRef = FirebaseDatabase.getInstance().getReference("Users/")
var userRef = databaseRef.child(uid)
userRef.addValueEventListener(object: ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
Log.e("first_name", snapshot.getValue(String::class.java))
}
...
Im trying to pull data from firebase realtime database but i'm not sure how to pull more than one data piece at the same time if its possible.
so this is what the database looks like:
so far i have managed to be able to print out all of these values in the following way:
private fun getData() {
var currentUid = mAuth.currentUser?.uid
val myRef = database.getReference("User-following").child(currentUid!!)
myRef.addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
val children = dataSnapshot.value
Log.e("Database", "value = $children")
}
override fun onCancelled(error: DatabaseError) {
Log.e("Database", error.toString())
}
})
}
when it prints the value of children i get all 5 in the following format:
E/Database: value = {-MLwcu81dicGo1NezqJD=1, -MLwcwBjdjRo-vgSkEjR=1, -MLwep1w5z4DfGeabx0d=1, -MLw_sc6aHPxPpGBIpCL=1, -MLwdqVch3iDr3GXylln=1}
how to i return each individual id so that i can use it to retrieve the data that corresponds to each id?
To access the individual child nodes under the snapshot you retrieved, you'll want to loop over its children.
override fun onDataChange(dataSnapshot: DataSnapshot) {
for (childSnapshot in dataSnapshot.children) {
Log.i("Database", "child key = $childSnapshot.key")
}
}
Also see the Firebase documentation on listening to value events.
I'm quite new at Kotlin. I have data class which hold image urls named testModel. I need to add data to model from firebase with that code:
Here my data model: class testModel(val imageLinks: List<String>)
private val dbRef = FirebaseDatabase.getInstance().reference.child("categories").child("1").child("top")
fun readDataFromFirebase(){
dbRef.addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
var list = ArrayList<testModel>()
for (e in dataSnapshot.children){
println(e.value)
}
}
override fun onCancelled(databaseError: DatabaseError) {
Log.e("DB", "loadPost:onCancelled", databaseError.toException())
}
})
}
Actually this block can get value from firebase I can see in run console my image urls but I can't add these on my testModel. How can I make it? Also I need good tutorials for these kind of works, like data models, read and write data with Kotlin. I am waiting for your advice.
PS: I already tried getValue method but is give error java.lang.
In your dataclass, change List<String> with ArrayList<String>, because the type List<E> does not exist in firebase, but arrays do.
Save your data as an Array<String> in firebase and then when you retrieve your snapshot, do snapshot.toObject(TestModel::class)
I'm trying to do the following in my Android application using Kotlin :
I have the Firebase data structure as shown in this image:
The user is able to choose 2 stations from the stations included in the data, either as "start_station", "end_station" or "station_number".. in the next function am trying to take the user's selections and check if both are encluded in the same line.
private fun fetchingLinesData(
theEndStation: String,
theStartStation: String,
) {
val database = FirebaseDatabase.getInstance()
val myRef = database.getReference("line")
myRef.addValueEventListener(object : ValueEventListener {
override fun onCancelled(p0: DatabaseError) {
toast(getString(R.string.could_not_find_a_way))
}
override fun onDataChange(p0: DataSnapshot) {
p0.children.forEach{
//Here should be the line that checks if both data exist
}
}
})
}
Tried using This hasChild Method but it wasn't right.
Try to convert your response to HashMap and search using containsValue
override fun onDataChange(p0: DataSnapshot) {
p0.children.forEach {
//Here should be the line that checks if both data exist
if(it.hasChildren()) {
val stationLines = it.value as HashMap<String, Any>
val validStart = stationLines.containsValue(theStartStation)
val validEnd = stationLines.containsValue(theEndStation)
...
}
}
}
You can do a query:
myRef.orderByChild("end_station").equalTo(theEndStation).addValueEventListener
This will retrieve the data according to the query, then inside onDataChange() after the forEach you can do the following:
if(p0.exists()){
// retrieve data here
}
Using exists() you can check if the datasnapshot exists.
This query will only check for end_station, if you want to check both, then after the query inside the if statement you can retrieve the first_station:
if(p0.exists()){
val firstStation = it.child("start_station").value
And check if firstStation is equal to theStartStation