Menu
Who Do Is
  • Home
  • What
  • How
  • Is
  • Can
  • Are
  • Does
  • Do
  • Why
  • Who
  • Where
  • Which
  • Which
  • Should
  • Will
  • When
  • What’s
  • Did
Who Do Is

[ANSWERED] android – How to display username from Firebase Realtime Database in Kotlin?

Posted on November 14, 2022

Solution 1 :

As I see in your database, the key of all User objects that are stored within Users node, are not added using the UID that comes from the authentication process, those key as generated with the push() method, because all of them start with -.

The most appropriate solution might be to change those keys and get then the data accordingly. To add a User object, you should some lines of code that looks like this:

val uid = FirebaseAuth.getInstance().currentUser!!.uid
val rootRef = FirebaseDatabase.getInstance().reference
val usersRef = rootRef.child("Users")
usersRef.child(uid).setValue(user)

To display the name of the logged-in users, simply use the following lines of code:

val valueEventListener = object : ValueEventListener {
    override fun onDataChange(dataSnapshot: DataSnapshot) {
        val name = dataSnapshot.child("name").getValue(String::class.java)
        Log.d("TAG", name)

        //Do what you need to do with the value of name
    }

    override fun onCancelled(databaseError: DatabaseError) {
        Log.d("TAG", databaseError.getMessage()) //Don't ignore errors!
    }
}
usersRef.child(uid).addListenerForSingleValueEvent(valueEventListener)

Solution 2 :

Try this code instead :

 val reference = FirebaseDatabase.getInstance().getReference("Users").child(auth?.currentUser?.uid)
    reference.addValueEventListener(object : ValueEventListener {
        override fun onDataChange(dataSnapshot: DataSnapshot) {
           for(snapshot in dataSnapShot.children){
          val username = 
               snapshot.child("username").value.toString()
            if (username == null)
                fragmentView?.name?.setText("Hello, Anonymous")
            else
                fragmentView?.name?.setText("Hello, $username")
        }        
                     }
          

        override fun onCancelled(databaseError: DatabaseError) {}
    })

Problem :

I am trying to display the current username from the Realtime Database but whenever I am running my code it gives me null. Here is my code:

    val reference =FirebaseDatabase.getInstance().reference
    currentUserUid = auth?.currentUser?.uid
    reference.addValueEventListener(object : ValueEventListener {
        override fun onDataChange(dataSnapshot: DataSnapshot) {
            val username =
                dataSnapshot.child(auth!!.currentUser!!.uid).child("Users")
                    .child("username")
                    .getValue(String::class.java)
            if (username == null)
                fragmentView?.name?.setText("Hello, Anonymous")
            else
                fragmentView?.name?.setText("Hello, $username")
        }

        override fun onCancelled(databaseError: DatabaseError) {}
    })

enter image description here

This is my content to code

package com.example.videoapp.Model

data class ContentDTO(var explain : String? = null,
                      var imageUrl : String? = null,
                      var uid : String? = null,
                      var userId : String? = null,
                      var username : String? = null,
                      var timestamp : Long? = null,
                      var favoriteCount : Int = 0,
                      var favorites : MutableMap<String,Boolean> = HashMap()){
    data class Comment(var uid : String? = null,
                       var userId : String? = null,
                       var comment : String? = null,
                       var timestamp : Long? = null)
}

This is my code where I can upload the pics. I have taken a little bit of help from the internet to do that. I am trying to display the name here but it’s returning nothing

val storageRef = storage?.reference?.child("images")?.child(imageFileName)
storageRef?.putFile(photoUri!!)?.continueWithTask { task: com.google.android.gms.tasks.Task<com.google.firebase.storage.UploadTask.TaskSnapshot> ->
    [email protected] storageRef.downloadUrl
}?.addOnSuccessListener { uri ->
    val contentDTO = com.example.videoapp.Model.ContentDTO()

    //Insert downloadUrl of image
    contentDTO.imageUrl = uri.toString()

    //Insert uid of user
    contentDTO.uid = auth?.currentUser?.uid

    //Insert userId
    contentDTO.userId = auth?.currentUser?.email
    contentDTO.username = auth?.currentUser?.displayName

    //Insert explain of content
    contentDTO.explain = addphoto_edit_explain2.text.toString()

    //Insert timestamp
    contentDTO.timestamp = System.currentTimeMillis()

    firestore?.collection("images")?.document()?.set(contentDTO)

    setResult(android.app.Activity.RESULT_OK)

    finish()
}

Comments

Comment posted by bhupen mallick

No sir codes are not working. Its returning nothing

READ  [ANSWERED] How can i create range seek bar in android java with indicator?
Powered by Inline Related Posts

Comment posted by Alex Mamo

In that case, please add a screenshot of your database to see the actual UID and not those pushed IDs, and also please edit your question to see the changed code you are using.

Comment posted by bhupen mallick

Sir I have added the screenshot of realtime database

Comment posted by Alex Mamo

You didn’t. I can still see the old one. Please the one where you have used the UIDs and not those pushed IDs.

Comment posted by Alex Mamo

Hi, bhupen! Have you tried my solution in my answer above?

Comment posted by bhupen mallick

No sir it is not working it’s returning “Hello null”

Comment posted by Taki

I have made an edit to my post , can you try again the new code now !

Comment posted by bhupen mallick

Sir when I am writing “for(snapshot in dataSnapShot)” then its returning error “For loop range must have an iterator method”

Comment posted by Taki

sorry my mistake buddy , you have to add .children to datasnapshot in the for loop , i editted the text , check it out again

Comment posted by bhupen mallick

No sir still its returning me nothing

Recent Posts

  • How can I play with my cat without toys?
  • What is a bag pipe band called?
  • Are Honda Civics actually fast?
  • Are Yankee candles toxic?
  • How do I pair my Michael Kors smartwatch with my Android?

Recent Comments

No comments to show.

Archives

  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022

Categories

  • ¿Cómo
  • ¿Cuál
  • ¿Cuántas
  • ¿Cuánto
  • ¿Que
  • ¿Quién
  • 90” and 108” so you may have to round up to the nearest size.
  • and delete any Spotify folders from it. Once this is done
  • Android
  • Are
  • At
  • Bei
  • blink
  • C'est
  • Can
  • carbs
  • Comment
  • Did
  • Do
  • Does
  • During
  • For
  • Has
  • How
  • In
  • Is
  • Ist
  • Kann
  • Können
  • nouveau
  • On
  • or 108 inches.2020-08-03
  • Où
  • owning
  • Pourquoi
  • Puis-je
  • Quand
  • Quante
  • Quel
  • Quelle
  • Quelles
  • Quels
  • Qui
  • Should
  • Sind
  • Sollte
  • spiritual
  • tap the downward-facing arrow on the top left. A downward-facing arrow will appear underneath each song in the album; they'll turn green as the download completes.2020-07-28
  • Uncategorized
  • Wann
  • Warum
  • Was
  • Welche
  • Welcher
  • Welches
  • Welke
  • Wer
  • Were
  • What
  • What's
  • When
  • Where
  • Which
  • Who
  • Whose
  • Why
  • Wie
  • Will
  • Wo
  • Woher
  • you will receive two curtains each with the same measurements of width 66"" (168cm) x drop 54""(137cm).
  • you'll see a green downward-facing arrow next to each song.2021-02-26
©2023 Who Do Is | Powered by SuperbThemes & WordPress