So, my app does is a QR code scanner that adds the QR id to the current user UID. I first verify if the user already did that scan; if not, that id is added to the firebase table; otherwise, it will create that table.
This is my code:
private fun infoAdd(str2: String, view: View) {
val currentUser = auth.currentUser?.uid
val postReference = FirebaseDatabase.getInstance().getReference("organsUsers")
val dbView = postReference.child(currentUser.toString())
val postListener = object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
val org = snapshot.child("uOrgans")
if (org != null) {
val post = org.getValue(String::class.java)
dbView.child("uOrgans").setValue("$post,$str2")
} else {
dbView.child("uOrgans").setValue(str2)
}
}
override fun onCancelled(databaseError: DatabaseError) {
}
}
dbView.addValueEventListener(postListener)
}
The str2 it's the string of the QR id.
This is what happens to Firebase:
Please Help!!!!
I first verify if the user already did that scan; if not, that id is added to the firebase table; otherwise, it will create that table.
It doesn't make any sense because in both cases you are "setting" the value of str2 into the database, that's why you see that behavior of highlighting that operation in yellow. Because a Firebase Realtime Database is a NoSQL database and is structured as pairs of keys and values, every node is a Map, which means that when using a setValue() operation, the old value is replaced with the new one.
If you want to check if the value of uOrgans exists, then update it for example, please use the following lines of code:
val uid = FirebaseAuth.getInstance().currentUser!!.uid
val rootRef = FirebaseDatabase.getInstance().reference
val uidRef = rootRef.child("organsUsers").child(uid)
val valueEventListener = object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
val org = snapshot.child("uOrgans")
if(org.exists()) {
val post = org.getValue(String::class.java)
dbView.getRef().updateChildren(mapOf("uOrgans" to "$post,$str2")) //Update it
Log.d("TAG", $post,$str2)
} else {
uidRef.child("uOrgans").setValue(str2)
}
}
override fun onCancelled(databaseError: DatabaseError) {
Log.d("TAG", databaseError.getMessage()) //Don't ignore potential errors!
}
}
uidRef.addListenerForSingleValueEvent(valueEventListener)
If doesn't exist, the str2 is added to the database.
One thing to mention, if uOrgans doesn't exist, none of its parents (organsUsers and the UID) nodes will not exist.
Related
I've been having problems accessing this child database in firebase, it always returns null, been searching online for days and still got no answer...here's my code, I'm using Kotlin and Firebase:
auth = FirebaseAuth.getInstance()
database = FirebaseDatabase.getInstance()
databaseReference = database?.reference!!.child("users")
val nikReference = databaseReference?.child("nik")
val mainDB = nikReference?.child("jabatan")
val user = auth.currentUser
etEmailUserShow.text = user?.email
mainDB?.addValueEventListener(object: ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
etValidasiLamaran.text = "Jabatan - - > "+snapshot.child("jabatan").value.toString() //<<-- this one returns null
}
heres my database configuration
Te structure is users/nik/... (the one I've highlighted red in the screenshot is nik).
What I want to access is the value likes of : berkas,ijasah,jabatan,etc etc.
To be able to display the data under a specific user, you have to create a reference that points exactly to that user. That being said, to display the data of the first user, please use the following lines of code:
val db = FirebaseDatabase.getInstance().reference
val nikRef = db.child("users").child("753951852")
val valueEventListener = object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
val jabatan = snapshot.child("jabatan").getValue(String::class.java)
Log.d("TAG", jabatan)
etValidasiLamaran.text = "Jabatan - - > " + jabatan
}
override fun onCancelled(error: DatabaseError) {
Log.d("TAG", error.getMessage()) //Never ignore potential errors!
}
}
nikRef.addListenerForSingleValueEvent(valueEventListener)
The result in the logcat will be:
POSISI : MASTER
I have a simple to-do app in Kotlin and I want to get data from "task" node in firebase on app startup. For each child, I want to create a Todo object.
var todo = Todo("child data here")
Getting specific task
val database = FirebaseDatabase.getInstance()
val ref = database.getReference("task")
var todo = ref.child("task1").key?.let { Todo(it) }
if (todo != null) {
todoAdapter.addTodo(todo)
}
I want to get all children, there can be more than three.
If you want to get all children of a particular node, no matter how many are actually present there, then you should loop over that node using getChildren() method, as you can see in the following lines of code:
val db = FirebaseDatabase.getInstance().reference
val taskRef = db.child("task")
val valueEventListener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
for (ds in dataSnapshot.children) {
val value = ds.getValue(String::class.java)
Log.d("TAG", value)
//Create the desired object
var todo = Todo(value) //👈
}
}
override fun onCancelled(error: DatabaseError) {
Log.d("TAG", error.getMessage()) //Never ignore potential errors!
}
}
taskRef.addListenerForSingleValueEvent(valueEventListener)
The result in the logcat will be:
task1
task2
task3
.....
I don't know why I got stuck in a problem that the chatList is not sorting by the last message time or by the most recent message. I have tried storing timestamp in the database and orderChildBy timestamp but it still not working. not working means the list get not sort after every message and keep showing the list as the sorted after first message.
Look at the image how chats are disordered!
This is the way I created chatList in the firebaseDatabase in ChatActiviy on sendMessage:
val timeAgo = Date().time
val myTimeMap = HashMap<String, Any?>()
myTimeMap["timestamp"] = timeAgo
myTimeMap["id"] = friendId
val friendTimeMap = HashMap<String, Any?>()
friendTimeMap["timestamp"] = timeAgo
friendTimeMap["id"] = currentUserID
val chatListSenderReference = dbRef.child("ChatList").child(currentUserID).child(friendId)
chatListSenderReference.keepSynced(true)
chatListSenderReference.addListenerForSingleValueEvent(object : ValueEventListener{
override fun onCancelled(p0: DatabaseError) {
}
override fun onDataChange(p0: DataSnapshot) {
if(!p0.exists()){
chatListSenderReference.updateChildren(friendTimeMap)
}
val chatListReceiverReference = dbRef.child("ChatList").child(friendId).child(currentUserID)
chatListReceiverReference.updateChildren(myTimeMap)
}
})
On retrieving the chatlist in recyclerView, I am trying to get the users details for each userswho is presented as the child of currentUser in database. (Chatlist>>CurrentUserId)
EDITED
private fun retrieveChatList() {
usersChatList = ArrayList()
val userRef = dbRef.child("ChatList").child(currentUserID).orderByChild("timestamp")
userRef.addValueEventListener(object : ValueEventListener
{
override fun onCancelled(error: DatabaseError) {
}
override fun onDataChange(snapshot: DataSnapshot)
{
(usersChatList as ArrayList<String>).clear()
if (snapshot.exists()){
for (dataSnapshot in snapshot.children){
val userUid = dataSnapshot.key
if (userUid != null) {
(usersChatList as ArrayList<String>).add(userUid)
}
}
readChatList()
}
}
})
}
private fun readChatList() {
mUsers = ArrayList()
val userRef = FirebaseFirestore.getInstance().collection("Users")
userRef.get()
.addOnSuccessListener { queryDocumentSnapshots ->
mUsers?.clear()
for (documentSnapshot in queryDocumentSnapshots) {
val user = documentSnapshot.toObject(User::class.java)
for (id in usersChatList!!){
if (user.getUid() == id){
(mUsers as ArrayList<User>).add(user)
}
}
}
retrieveGroupChatList()
chatListAdapter?.notifyDataSetChanged()
chatListAdapter = context?.let { ChatListAdapter(it, (mUsers as ArrayList<User>), true) }
recyclerViewChatList.adapter = chatListAdapter
}.addOnFailureListener { e ->
Log.d(ContentValues.TAG, "UserAdapter-retrieveUsers: ", e)
}
}
And this is the chatListAdapter for friend info
private fun friendInfo(fullName: TextView, profileImage: CircleImageView, uid: String) {
val userRef = FirebaseFirestore.getInstance().collection("Users").document(uid)
userRef.get()
.addOnSuccessListener {
if (it != null && it.exists()) {
val user = it.toObject(User::class.java)
Picasso.get().load(user?.getImage()).placeholder(R.drawable.default_pro_pic).into(profileImage)
fullName.text = user?.getFullName()
}
}
}
This is the picture of the realtime database and has a model class as ChatList, every time when I send or receive a message timestamp gets an update.
and another picture of Users in the firestore and has a model class as Users .
SOLUTION
I have a solution which works, Here i create or update a field as lastMessageTimestamp in the Firestore Users collection so the users now can sort by the lastMessageTimestamp .
val timeAgo = Date().time
val myFSMap = HashMap<String, Any?>()
myFSMap["timestamp"] = timeAgo
val friendFSMap = HashMap<String, Any?>()
friendFSMap["timestamp"] = timeAgo
//firebase chatlist references.
val chatListSenderReference = dbRef.child("ChatList").child(currentUserID).child(friendId)
val chatListReceiverReference = dbRef.child("ChatList").child(friendId).child(currentUserID)
//Firestore Users references.
val chatListSenderRef = fStore.collection("Users").document(currentUserID)
val chatListReceiverRef = fStore.collection("Users").document(friendId)
chatListSenderReference.addListenerForSingleValueEvent(object : ValueEventListener{
override fun onDataChange(p0: DataSnapshot) {
if(!p0.exists()){
chatListSenderReference.setValue(friendId)
//update the timestamp in Users collection
chatListSenderRef.update(myFSMap)
}
chatListReceiverReference.setValue(currentUserID)
chatListReceiverRef.update(friendFSMap)
override fun onCancelled(p0: DatabaseError) {
}
}
})
And at the time of reading, I use orderBy for Users
val userRef = FirebaseFirestore.getInstance().collection("Users").orderBy("lastMessageTimestamp" , Query.Direction.ASCENDING)
But It is not the complete solution because it seems like that i read and write the lastMessageTimestamp each time on messaging, which can Increase the Firebase Billing Amount to huge scary numbers. so i still need of a solution.
Simple trick is orderBy id of message. Because the id which generated by firebase base on realtime + a few factors. So let's try order by Id instead of ur timestamp. (note: just id which generated by firebase)
enter code hereSaw your post don't know if it might be useful this late hour, provided the only thing you want from firestone is the user full identity, like the name, picture etc use the userid and save the full details to android database then retrieve the identity using the Id from chatlist firebase database that matches userid
Your code might look like this
Read from chatlist firebase database
Retrieve the sender Id and time
Use the id to retrieve already added info of the person on android database
your model should contain variable for retrieve time from database
Then add all to list
After that use a comparator to sort the arraylist/list base on time
Then notify adapter change
{` ......
userDao = UserDatabase.getUserDatabase(requireContext()).userDao();
}
private void sortChatList() {
reference.child("chatlist").child(firebaseUser.getUid()).orderByChild("time").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
list.clear();;
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
String userID = Objects.requireNonNull(snapshot.child("chatid").getValue()).toString();
String time = snapshot.child("time").getValue().toString();
Chatlist chatlist = new Chatlist();
UserDB userDB = userDao.getAll(userID);
chatlist.setDate(time);
chatlist.setUserName(userDB.getUserName());
chatlist.setUserID(userID);
list.add(chatlist);
}
Collections.sort(list, new Comparator<Chatlist>() {
#Override
public int compare(Chatlist o1, Chatlist o2) {
return Integer.valueOf(o2.getTime().compareTo(o1.getTime()));
}
});
if (adapter != null) {
adapter.notifyDataSetChanged();
.........
`}
I need to get from the Firebase Realtime Database node, not the entire list, but only the one that contains the value "ok".
I can get the whole list using the User model
val list:List<User> = it.children.map {it.getValue(User::class.java)}
If you need to get only the users that have the id property set to "ok", then you should use a Query line in the following lines of code:
val rootRef = FirebaseDatabase.getInstance().reference
val usersRef = rootRef.child("users")
val okQuery = usersRef.orderByChild("id").equalTo("ok")
val valueEventListener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
for (ds in dataSnapshot.children) {
val user = ds.getValue(User::class.java)
Log.d("TAG", ds.key + " -> " + user.id)
}
}
override fun onCancelled(databaseError: DatabaseError) {
Log.d("TAG", databaseError.getMessage()) //Don't ignore errors!
}
}
okQuery.addListenerForSingleValueEvent(valueEventListener)
The result in the logcat will be:
kolya -> ok
sasha -> ok
I have two methods, in one I create a new list item, in the second I update the current list item.
private fun addTarget() {
val name = nameEditText?.text.toString().trim()
val description = descriptionEditText?.text.toString().trim()
if (!TextUtils.isEmpty(name)) {
val id: String = databaseReference?.push()?.key.toString()
val target = Target(guid = id, name = name, description = description)
databaseReference?.child(id)?.setValue(target)
} else Log.d("some", "Enter a name")
}
private fun updateTarget() {
val name = nameEditText?.text.toString().trim()
val description = descriptionEditText?.text.toString().trim()
val map = mapOf("name" to name, "description" to description)
databaseReference?.child(arguments?.getString(KEY_TARGET_GUID, "") ?: "")?.updateChildren(map)
}
I need to clearly separate these two concepts, so there is a problem in the condition.
button?.setOnClickListener { if (condition?????) addTarget() else updateTarget() }
For example, in the Realm there is a method copyToRealmOrUpdate which looks for the field and if it finds it updates it if not then creates a new note. How can I do something like this in firebase?
I resolved my problem next:
When I go to the fragment I pass the guid from the list of all elements and if it is empty then I add if not then update.
button?.setOnClickListener {
if (arguments?.getString(KEY_TARGET_GUID, "").isNullOrEmpty()) addTarget()
else updateTarget()
}
I don't know how this is a good solution.
This is possible in Firebase if you are using exist() method like in the following lines of code:
val valueEventListener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
if (dataSnapshot.exists()) {
//Do the update
} else {
//Do the addition
}
}
override fun onCancelled(databaseError: DatabaseError) {
Log.d(TAG, databaseError.getMessage()) //Don't ignore errors!
}
}
databaseReference.child("-LaVYDBpwiIcwhe9qz2H").addListenerForSingleValueEvent(valueEventListener)