BÀI 39 - ĐỌC VÀ NHẬP DỮ LIỆU LÊN FIREBASE TRONG LẬP TRÌNH ANDROID

  1. Realtime Database

Đầu tiên, vào Gradle (app) thêm thư viện của Realtime Database sau:

implementation 'com.google.firebase:firebase-database'

implementation 'com.google.firebase:firebase-database:20.0.0'

1.1. Truy cập dữ liệu Firebase

DatabaseReference tenbien1 = FirebaseDatabase.getInstance();

1.2. Truy cập dữ liệu từ thẻ từ đầu tiên

DatabaseReference tenbien2 = FirebaseDatabase.getInstance().getReference("tên thẻ");

  • Truy cập đến các thẻ là bước đầu tiên để lấy giá trị từ các thẻ này. Các giá trị (value) có thể có trong thẻ đầu tiên hoặc các thẻ đầu tiên này còn có các thẻ con khác nữa.

  • Nếu thẻ đầu tiên có giá trị thì: tenbien1.getValue(); để lấy giá trị của nó.

  • Nếu nó chứa các thẻ con thì bạn làm tiếp như bên dưới:

1.3. Đọc dữ liệu từ các thẻ con

DatabaseReference tenbien2 = FirebaseDatabase.getInstance().getReference("tên thẻ");

tenbien2.addListenerForSingleValueEvent(new ValueEventListener() {

@Override

public void onDataChange(@NonNull DataSnapshot snapshot) {

if (snapshot.exists()) {

String tenbien3 = snapshot.child("tenthe").getValue(String.class);

Int tenbien4 = snapshot.child("tenthe").getValue();

TextView.setText(tenbien3);

}

}

@Override

public void onCancelled(@NonNull DatabaseError error) {

}

});

//----------------------------------------------------------------------------------------

addListenerForSingleValueEvent() //Đọc 1 lần rồi thôi

addValueEventListener() //Đọc liên tục trong vòng lặp

1.4. Lấy toàn bộ dữ liệu

  • Đầu tiên bạn cũng phải truy suất đến thẻ mong muốn.

  • Chạy vòng for như thể này

DatabaseReference tenbien2 = FirebaseDatabase.getInstance().getReference("tên thẻ");

tenbien2.addListenerForSingleValueEvent(new ValueEventListener() {

@Override

public void onDataChange(@NonNull DataSnapshot snapshot) {

if (snapshot.exists()){

for (DataSnapshot data : snapshot.getChildren()){

String key = data.getKey();

Object value = data.getValue();

arrayList.add(key + " - " + value);

}

adapter.notifyDataSetChanged(); //Cập nhật lại arrayList bằng adapter

} else {

Toast.makeText(YourActivity.this,

"Thẻ không có dữ liệu", Toast.LENGTH_SHORT).show();

}

}

@Override

public void onCancelled(@NonNull DatabaseError error) {

}

});

1.5. Nhập dữ liệu

DatabaseReference tenbien2 = FirebaseDatabase.getInstance().getReference("tên thẻ");

tenbien2.setValue(); // Nếu không có thẻ con

tenbien2.child("tên thẻ").setValue(); // Nếu có thẻ con