---
# System prepended metadata

title: 'Firebase with Android Studio part-2 : a simple register demo'
tags: [Firebase, Android, kotlin]

---

# Firebase with Android Studio part-2 : a simple register demo

## 開始吧

### gradle 新增依賴
* 註冊會用到coroutine背景執行
```kotlin=

implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.1.1'
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.3'
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.3'
```

### 畫個簡單的UI吧

![](https://i.imgur.com/EGnXO4V.png)

### 到firebase console 啟用
* 這邊用簡易的信箱跟密碼

![](https://i.imgur.com/RMrQ3YU.png)

### 再來就可以寫功能了
* 主要是透過firebaseAuth的createUserWithEmailAndPassword函數完成註冊
* 註冊成功之後，妳可以在firebase console看到你剛剛註冊的user資訊

```kotlin=
class MainActivity : AppCompatActivity() {
    
    //這裡要先宣告Firebasae object
    lateinit var auth: FirebaseAuth

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        //取得instance
        auth = FirebaseAuth.getInstance()

        findViewById<Button>(R.id.bt_register).setOnClickListener {
            registerUser()
        }
    }

    //簡易註冊功能
    private fun registerUser(){
        val email = findViewById<EditText>(R.id.ed_regMail).text.toString().trim()
        val pwd = findViewById<EditText>(R.id.ed_regPwd).text.toString()
        if(email.isNotEmpty() && pwd.isNotEmpty()){
            CoroutineScope(Dispatchers.IO).launch {
                try {
                    auth.createUserWithEmailAndPassword(email,pwd).await()
                    withContext(Dispatchers.Main){
                        checkLoggedInStatus()
                    }
                }catch (e:Exception){
                    withContext(Dispatchers.Main){
                        Toast.makeText(this@MainActivity, e.message, Toast.LENGTH_LONG).show()
                    }
                }
            }
        }
    }

    private fun checkLoggedInStatus() {
       if (auth.currentUser == null){
           findViewById<TextView>(R.id.tv_status).text = "你尚未登入"
       }else{
           findViewById<TextView>(R.id.tv_status).text = "成功登入登入"
       }

    }

}
```

![](https://i.imgur.com/Z7CCBPk.png)

* 在寫登入的功能

```kotlin=
findViewById<Button>(R.id.bt_login).setOnClickListener {
            logInUser()
        }
        
    private fun logInUser(){
    val email = findViewById<EditText>(R.id.ed_loginMail).text.toString().trim()
    val pwd = findViewById<EditText>(R.id.ed_login_pwd).text.toString()
    if(email.isNotEmpty() && pwd.isNotEmpty()){
        CoroutineScope(Dispatchers.IO).launch {
            try {
                auth.signInWithEmailAndPassword(email,pwd).await()
                withContext(Dispatchers.Main){
                    checkLoggedInStatus()
                }
            }catch (e:Exception){
                withContext(Dispatchers.Main){
                    Toast.makeText(this@MainActivity, e.message, Toast.LENGTH_LONG).show()
                }
            }
        }
    }
}

```
* 在類別override 
    * 因為firebase預設在你重啟app時，他的登入狀態預設是保留在登入狀態，可以透過onStart去檢查狀態

```kotlin=
override fun onStart() {
        super.onStart()
        checkLoggedInStatus()
    }
```

* 解法就是在每次activity onCreate就登出

```kotlin=
override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        auth = FirebaseAuth.getInstance()
        
        //只需要新增下面這一行就可以確保每次重啟就登出
        auth.signOut()
```
### 以上就是簡易的登入demo

###### tags: `Firebase` `kotlin` `Android`