0

I am a beginner to android programming, learning on my own. I am using android studio 4.1.1' and kotlin`.

I followed a tutorial to create a Firebase login setup.

... in part...

private var mAuth: FirebaseAuth? = null
...
// in override fun onCreate()
mAuth = FirebaseAuth.getInstance()

// once a user is logged in, I can do:
val userID = mAuth!!.currentUser!!.uid

The tutorial (and other tutorials and threads) did not cover whether the mAuth!!.currentUser!!.uid persists across multiple Activities or Fragments. Is this possible? How do I check for the currentUser on any given .kt file?

I could create a Global class with a companion object{} and set Global.userID = "test" then once I a user is logged in, I could set Global.userID = mAuth!!.currentUser!!.uid, but that doesn't seem like the best option.

Thanks for any advice or pointers.

John Cowan
  • 1,452
  • 5
  • 25
  • 39
  • Personally I don’t find it too troubling to test whether Auth.auth().currentUser is null or not. No apparent need to go global. – Dan Abnormal Jan 19 '21 at 20:08
  • But on the other hand - if you’re thinking about gathering together some frequently used user methods - fun userIsLoggedIn() : Boolean { return Auth.auth().currentUser != null} could perhaps be something – Dan Abnormal Jan 19 '21 at 20:15
  • You should use an AuthStateListener, to check the state of the user. This can be made no matter it's a fragment or an activity. Please check the duplicate. – Alex Mamo Jan 20 '21 at 00:09
  • @DanAbnormal How do I get `Auth.auth().currentUser` to work in my second fragment? It shows in red with not solutions that I understand. Is there some package I need to import? It does not prompt me for any. – John Cowan Jan 22 '21 at 13:19
  • @JohnCowan I'm sorry, I used iOS code. I meant to write that you can check if FirebaseAuth.getInstance().currentUser is not null. You can do this anywhere in your app – Dan Abnormal Jan 22 '21 at 14:36
  • @DanAbnormal Thanks and no worries. Scary to say, I'm enjoying learning this stuff. "I THINK" I did try that one: `FirebaseAuth.getInstance().currentUser`. But, I tried a lot of things. I will try it for sure now. – John Cowan Jan 22 '21 at 15:29
  • As far as I understand it should work; if currentUser != null a user is logged in – Dan Abnormal Jan 22 '21 at 15:31
  • @DanAbnormal Thank you for all your help. This is working now. – John Cowan Jan 22 '21 at 21:27
  • Glad to hear that. Good luck! – Dan Abnormal Jan 22 '21 at 21:31

0 Answers0