How can I get data from firebase to data model? - android

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)

Related

how to get all child with specific value from Firebase android kotlin?

I want to get just color item in the image from all user in my database. I try this
private fun setListPersonOfferService(){
val database = FirebaseDatabase.getInstance()
val userIdReference = database.getReference("user personal data").child("Country")
val userFilterListener = object : ValueEventListener {
override fun onCancelled(databaseError: DatabaseError) {
// handle error
}
override fun onDataChange(dataSnapshot: DataSnapshot) {
val listTest = dataSnapshot.children.map { it.getValue(HomePageModel::class.java)!! }
itemAdapter = ItemAdapterHomePage(context ?: return,
listTest as ArrayList<HomePageModel>
)
itemAdapter?.onItemClick = {
Supplier.serviceList[it].state = !Supplier.serviceList[it].state
itemAdapter?.notifyDataSetChanged()
Toast.makeText(context, "go to speck", Toast.LENGTH_LONG).show()
}
recyclerView_homePage.apply {
layoutManager = LinearLayoutManager(context)
adapter = itemAdapter
}
}
}
userIdReference.addListenerForSingleValueEvent(userFilterListener)
}
class HomePageModel(var lastName: String?=null,
var town: String?=null,
var faculty: String?=null,
var languageOfStudy: String?=null )
if i change Reference to the specific directory .child("Turcia").child("Adana").child("Çukurova University").child("Faculty of Business") it works, but i want to get from all user.
You'll need to navigate over the dataSnapshot in your onDataChange to get to the correct child nodes.
To navigate a DataSnapshot object you have two main approaches:
You already know the key of the child you want to access, in which case you use the child() method to access that specific child node. For example, you could read the marked child in the JSON with dataSnapshot.child("Turcia/Adana/Çukurova University/Faculty of Business").children.map, similarly to what you already tried on the reference.
You don't know the key of the child nodes, in which case you loop over the getChildren() property of the snapshot. For an example of the latter, see the Firebase documentation on listening for value events on a list of children.
I think you're looking for the second approach here, but in any case you're dealing with DataSnapshots, there are the ways to get at the data in there.

how to get some child list from Firebase android kotlin?

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.

how do i retrieve data from firebase realtime database using kotlin

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.

how to check if firebase have value1 and value2 exist

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

How to retrieve data from a Firebase database with Kotlin?

This is the model I upload on Firebase:
public class OnlineMatch{
private User user1;
private User user2;
public OnlineMatch(User firstPlayer, User secondPlayer) {
this.user1 = firstPlayer;
this.user2 = secondPlayer;
}
}
Then I send data to Firebase in this way (kotlin):
fun createMatch(match: OnlineMatch) {
val matchList = database.child("multiplayer").push()
matchList.setValue(match)
}
Thus, my DB structure is the following:
If I expand a node I can see perfectly my objects: OnlineMatch(User1, User2)
Now I would like to query the db and obtain an ArrayList'<'OnlineMatch'>'.
I have already found the Firebase docs but I found nothing useful.
How can I do? Thanks in advance.
You did not find something useful because when you query against a Firebase database you get a Map and not ArrayList. Everything in Firebase is structured as pairs of key and value. Using an ArrayList is an anti-pattern when it comes to Firebase. One of the many reasons Firebase recommends against using arrays is that it makes the security rules impossible to write.
In Kotlin there is no need for getters and setters. Is true that behind the scenes those functions exists but there is no need to explicitly define them. To set those fields, you can use the following code:
val onlineMatch = OnlineMatch() //Creating an obect of OnlineMatch class
onlineMatch.user1 = userObject //Setting the userObject to the user1 field of OnlineMatch class
//onlineMatch.setUser(userObject)
As you probably see i have commented the last line because there is no need to use a setter in order to set a userObject.
And very important, don't forget to add the no argument constructor in your OnlineMatch class that is needed for Firebase.
public OnlineMatch() {}
Edit:
To actually get the data, just put a listener on the desired node and get the data out from the dataSnapshot object into a HashMap.
val map = HashMap<String, OnlineMatch>()
Then simply iterate over the HashMap like this:
for ((userId, userObject) in map) {
//do what you want with them
}
Or simply use the code below:
val rootRef = firebase.child("multiplayer")
rootRef.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onCancelled(error: FirebaseError?) {
println(error!!.message)
}
override fun onDataChange(snapshot: DataSnapshot?) {
val children = snapshot!!.children
children.forEach {
println(it.toString())
}
}
})
Hope it helps.

Categories

Resources