---
# System prepended metadata

title: 'Firebase with Android Studio part-3 : update Profile'
tags: [Firebase, Android, kotlin]

---

# Firebase with Android Studio part-3 : update Profile

## 開始吧

### gradle UI畫面調整
* 增加一個image View
* 透過輸入名稱，更新顯示圖片，之後登入會自動帶入圖片跟名稱
![](https://i.imgur.com/KbqapRH.png)


### 繼上篇的架構新增功能
* 透過UserProfileChangeRequest打包我們要更新的資料
* 最後由current User呼叫 updateProfile把剛剛打包的資料更新到firebase
```kotlin=
    findViewById<Button>(R.id.bt_updateProfile).setOnClickListener {
                updateProfile()
    }

private fun updateProfile(){
        auth.currentUser?.let { user ->
            val username = findViewById<EditText>(R.id.ed_updateProfile).text.toString()
            val photoUri = Uri.parse("android.resource://$packageName/${R.drawable.ic_baseline_accessibility_new_24}")
            val profileUpdate = UserProfileChangeRequest.Builder()
                .setDisplayName(username)
                .setPhotoUri(photoUri)
                .build()

            CoroutineScope(Dispatchers.IO).launch {
                try {
                    user.updateProfile(profileUpdate).await()
                    withContext(Dispatchers.Main){
                        checkLoggedInStatus()
                        Toast.makeText(this@MainActivity,"更新成功",Toast.LENGTH_LONG).show()
                    }

                }catch (e:Exception){
                    withContext(Dispatchers.Main){
                        Toast.makeText(this@MainActivity,"更新失敗",Toast.LENGTH_LONG).show()
                    }
                }
            }
        }
    }
    
    private fun checkLoggedInStatus() {
        val user = auth.currentUser
       if (user == null){
           findViewById<TextView>(R.id.tv_status).text = "你尚未登入"
       }else{
           findViewById<TextView>(R.id.tv_status).text = "成功登入"
           findViewById<EditText>(R.id.ed_updateProfile).setText(user.displayName)
           findViewById<ImageView>(R.id.imageView).setImageURI(user.photoUrl)
       }

    }
```

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