將 Firebase 實時資料庫與 Android 應用程式整合
如何在 Android 應用程式中實現 Firebase 實時資料庫。
設定/安裝:
- 
首先,安裝 Firebase SDK( 指南 ) 
- 
使用 Firebase 控制檯註冊你的專案 
- 
成功完成上述兩個步驟後,在應用程式級別 1 中新增以下依賴項。 compile 'com.google.firebase:firebase-database:9.2.1'
- 
[可選]配置資料庫安全規則( 參考 )。 
實施示例:
- 
宣告並初始化資料庫引用 FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference myRef = database.getReference("message");
你可以稍後建立不同的引用以訪問不同的節點
- 
將新資料寫入資料庫 myRef.setValue("Writing Demo");
- 
從資料庫中讀取資料 myRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { // This method is called once with the initial value and again // whenever data at this location is updated. String value = dataSnapshot.getValue(String.class); Log.d(TAG, "Value is: " + value); } @Override public void onCancelled(DatabaseError error) { // Failed to read value Log.w(TAG, "Failed to read value.", error.toException()); } });