# Firebase with Android Studio part-5 : Using FireStore to save data ## 開始吧 ### 前置作業 * 參考[Part-1](https://hackmd.io/OVJ6GLpPR_Kb5kA-85kdgQ?view) * 但這次主角是Cloud FireStore  ### UI就簡單配置吧  ### 定義data class ```kotlin= data class Person( var firstName: String, var lastName: String, var age: Int ) ``` ### 功能實作 * 新增資料使用 CollectionReference的add功能就完成了 ```kotlin= class MainActivity : AppCompatActivity() { //定義fireStore要儲存資料的參照路徑 private val personCollectionRef = Firebase.firestore.collection("Persons") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) findViewById<Button>(R.id.upload).setOnClickListener { val firstName = findViewById<EditText>(R.id.ed_firstName).text.toString() val lastName = findViewById<EditText>(R.id.ed_lastName).text.toString() val age = findViewById<EditText>(R.id.ed_age).text.toString().toInt() savePerson(Person(firstName, lastName, age)) } } private fun savePerson(person: Person) = CoroutineScope(Dispatchers.IO).launch { try { personCollectionRef.add(person).await() withContext(Dispatchers.Main){ Toast.makeText(this@MainActivity,"儲存成功", Toast.LENGTH_LONG).show() } }catch (e:Exception){ withContext(Dispatchers.Main){ Toast.makeText(this@MainActivity,e.message, Toast.LENGTH_LONG).show() } } } } ``` ### 到fireStore建立資料庫  * 我先以測試模式啟用  * 選擇伺服器位置,會根據所在地影響讀寫速度  * 剛建立完成,是一個空的集合  ### 執行app  * 當Toast顯示成功之後,重新整理foreStore就會看到剛剛新增的資料了  * 再新增第二筆資料看看~~  ### 看看FireStore的資料結構 * 它的集合(collection)像是我們一般資料庫的資料表(Table) * 它的文件(document)像是資料表裡面的單一筆資料,每個文件的ID都是唯一的。 ###### tags: `Firebase` `kotlin` `Android`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up