Szukaj…


Dodaj bazę danych w czasie rzeczywistym w systemie Android

  1. Zakończ instalację i konfigurację, aby połączyć aplikację z Firebase.
    Spowoduje to utworzenie projektu w Firebase.

  2. Dodaj zależność dla Firebase Realtime Database do pliku build.gradle poziomie modułu:

compile 'com.google.firebase:firebase-database:9.2.1'
  1. Skonfiguruj reguły bazy danych Firebase

Teraz jesteś gotowy do pracy z bazą danych Realtime w systemie Android.

Na przykład piszesz wiadomość Hello World do bazy danych pod kluczem message .

// Write a message to the database
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("message");

myRef.setValue("Hello, World!");

Używanie setValue do zapisywania danych

Metoda setValue() zastępuje dane w określonej lokalizacji, w tym wszystkie węzły podrzędne.

Możesz użyć tej metody do:

  1. Przekaż typy odpowiadające dostępnym typom JSON w następujący sposób:
  • Strunowy
  • Długo
  • Podwójnie
  • Boolean
  • Mapa <Ciąg, Obiekt>
  • Lista
  1. Przekaż niestandardowy obiekt Java, jeśli klasa, która go definiuje, ma domyślny konstruktor, który nie przyjmuje argumentów i ma publiczne moduły pobierające dla przypisanych właściwości.

To jest przykład z CustomObject.
Najpierw zdefiniuj obiekt.

@IgnoreExtraProperties
public class User {

    public String username;
    public String email;

    public User() {
        // Default constructor required for calls to DataSnapshot.getValue(User.class)
    }

    public User(String username, String email) {
        this.username = username;
        this.email = email;
    }

Następnie pobierz odwołanie do bazy danych i ustaw wartość:

   User user = new User(name, email);
   DatabaseReference mDatabase mDatabase = FirebaseDatabase.getInstance().getReference();
   mDatabase.child("users").child(userId).setValue(user);

Przykład wstawiania danych lub pobierania danych z Firebase

Zanim zrozumiesz, musisz postępować zgodnie z niektórymi ustawieniami integracji projektu z firebase.

  1. Utwórz projekt w konsoli Firebase i pobierz plik google-service.json z konsoli i umieść go w module poziomu aplikacji swojego projektu, kliknij link Utwórz projekt w konsoli

  2. Następnie musimy dodać trochę zależności w naszym projekcie,

  • Najpierw dodaj ścieżkę klasy w naszej klasie na poziomie projektu,

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

  • A potem zastosuj wtyczkę na poziomie aplikacji, napisz poniżej sekcji zależności,

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

  • Istnieje więcej zależności, które wymagają dodania poziomu aplikacji w sekcji zależności

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

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

  • Teraz zacznij wstawiać dane do bazy danych Firebase. Najpierw musisz utworzyć instancję

    FirebaseDatabase database = FirebaseDatabase.getInstance();

    po utworzeniu obiektu FirebaseDatabase utworzymy naszą bazę danych DatabaseReference do wstawiania danych do bazy danych,

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

    Tutaj student jest nazwą tabeli, jeśli tabela istnieje w bazie danych, a następnie wstaw dane do tabeli, w przeciwnym razie utwórz nową z nazwą studenta, po czym możesz wstawić dane za pomocą databaseReference.setValue(); działają jak śledzenie,

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

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

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

    databaseReference.setValue(student);

    Tutaj wstawiam dane jako mapę mapy, ale możesz również ustawić jako klasę modelu,

  • Zacznij jak odzyskiwać dane z bazy ogniowej, używamy tutaj addListenerForSingleValueEvent do odczytu wartości z bazy danych,

      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) {
    
              }
          });
    

Uzyskaj wartość / s z bazy ogniowej

  1. Utwórz klasę i dodaj import do informacji o analizie:
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.IgnoreExtraProperties;

//Declaration of firebase references
private DatabaseReference mDatabase;

//Declaration of firebase atributtes
public String uID;
public String username;
public String email;

@IgnoreExtraProperties
public class User {

    //Default constructor
    public User() {

        //Default constructor required for calls to DataSnapshot.getValue(User.class)
        mDatabase = FirebaseDatabase.getInstance().getReference();

        //...
    }

    //...
}
  1. Dodaj addListenerForSingleValueEvent() do naszego odwołania do bazy danych:
//Add new imports
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.ValueEventListener;

//...

public void getUser(String uID){

    //The uID it's unique id generated by firebase database
    mDatabase.child("users").child(uID).addListenerForSingleValueEvent(
            new ValueEventListener () {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                // ...
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                // Getting Post failed, log a message
            }
    });
}
  1. Napompuj naszą klasę informacjami onDataChange() w onDataChange() :
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            //Inflate class with dataSnapShot
            Users user = dataSnapshot.getValue(Users.class);

            //...
        }
  1. Wreszcie możemy normalnie uzyskać różne atrybuty z klasy firebase:
//User inflated
Users user = dataSnapshot.getValue(Users.class);

//Get information
this.uID = user.uID;
this.username = user.username;
this.email = user.email;

Najlepsze praktyki

  1. Baza ogniowa obsługuje 32 różne poziomy potomne, a następnie łatwo jest napisać niepoprawnie referencje, aby uniknąć tego, utworzyć ostateczne prywatne referencje:
//Declaration of firebase references
//...
final private DatabaseReference userRef = mDatabase.child("users").child("premium").child("normal").getRef();

//...

public void getUser(String uID){

    //Call our reference
    userRef.child(uID).addListenerForSingleValueEvent(
        new ValueEventListener () {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                // ...
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                // Getting Post failed, log a message
            }
    });
}
  1. onCancelled() jest wywoływane, gdy użytkownik nie ma dostępu do tego odwołania na podstawie reguł bazy danych. Dodaj odpowiedni kod, aby kontrolować ten wyjątek, jeśli potrzebujesz.

Aby uzyskać więcej informacji, odwiedź oficjalną dokumentację



Modified text is an extract of the original Stack Overflow Documentation
Licencjonowany na podstawie CC BY-SA 3.0
Nie związany z Stack Overflow