從 Firebase 進行資料插入或資料檢索的示例

在瞭解之前需要遵循一些與 firebase 整合的專案設定。

  1. 在 Firebase 控制檯中建立專案並從控制檯下載 google-service.json 檔案並將其放入專案的應用級模組中,在控制檯中按照建立專案的連結

  2. 在此之後我們需要在專案中新增一些依賴項,

  • 首先在專案級 gradle 中新增類路徑,

    classpath 'com.google.gms:google-services:3.0.0'

  • 然後在 app level levell 中應用外掛,將其寫在依賴部分下面,

    apply plugin: 'com.google.gms.google-services

  • 需要在依賴部分新增應用級別 gradle 的更多依賴性

    compile 'com.google.firebase:firebase-core:9.0.2'

    compile 'com.google.firebase:firebase-database:9.0.2'

  • 現在開始在 firebase 資料庫中插入資料,首先要求建立例項

    FirebaseDatabase database = FirebaseDatabase.getInstance();

    在建立 FirebaseDatabase 物件之後,我們將建立 DatabaseReference 以在資料庫中插入資料,

    DatabaseReference databaseReference = database.getReference().child("student");

    這裡 student 是表名,如果表存在於資料庫中然後將資料插入表中,否則建立一個帶有學生名的新表,之後你可以使用 databaseReference.setValue(); 函式插入資料如下,

    HashMap<String,String> student=new HashMap<>();

    student.put("RollNo","1");

    student.put("Name","Jayesh");

    databaseReference.setValue(student);

    這裡我將資料作為 hasmap 插入但你也可以設定為模型類,

  • 開始如何從 firebase 中檢索資料,我們在這裡使用 addListenerForSingleValueEvent 來讀取資料庫中的值,

      senderRefrence.addListenerForSingleValueEvent(new ValueEventListener() {
              @Override
              public void onDataChange(DataSnapshot dataSnapshot) {
                  if(dataSnapshot!=null && dataSnapshot.exists()){
                      HashMap<String,String> studentData=dataSnapshot.getValue(HashMap.class);
                      Log.d("Student Roll Num "," : "+studentData.get("RollNo"));
                      Log.d("Student Name "," : "+studentData.get("Name"));
                  }
              }
    
              @Override
              public void onCancelled(DatabaseError databaseError) {
    
              }
          });