How to enable Firebase persistence offline

Asked

Viewed 863 times

0

I’m having trouble enabling firebase’s offline data persistence in my app. The problem is this, I have an auxiliary class called Configurationfirebase which starts the required firebase objects, to make queries and save data using Databasereference or Query, and I would like that when I read the database it made available that data offline, follows an example of the classes used:

public final class ConfiguracaoFirebase {

private static FirebaseDatabase database;
private static FirebaseStorage storage;
static DatabaseReference reference;
private static StorageReference storageReference;

public ConfiguracaoFirebase(){

}

public static DatabaseReference getFirebaseReference(){
    if (reference == null){
        reference = FirebaseDatabase.getInstance().getReference();
    }

    return reference;
}

public static StorageReference getStorageReference(){
    if (storageReference == null){
        storage = FirebaseStorage.getInstance();
        storageReference = storage.getReferenceFromUrl("gs://herdeirosapp.appspot.com/").child("GALERIA");
    }
    return storageReference;
}

public static FirebaseDatabase getDatabase(){
    if (database != null){
        database = FirebaseDatabase.getInstance();
        database.setPersistenceEnabled(true);
        //FirebaseDatabase.getInstance().setPersistenceEnabled(true);
    }
    return database;
}
}

The function of the model class that saves the data in realtimeDatabase:

public void salvarPlacar(){
    //Pegando o ano atual
    Date ano = Calendar.getInstance().getTime();
    DateFormat format = new SimpleDateFormat("yyyy");
    String anoRetiro = format.format(ano);

    String cripto = CriptografiaBase64.criptografarData(atualizacao);

    DatabaseReference reference = ConfiguracaoFirebase.getFirebaseReference();
    reference.child("RETIRO")
            .child(anoRetiro)
            .child("PLACAR")
            .child(cripto)
            .setValue(this);
}

And the Activity that brings the data in this example I do a query to bring the latest data, and I’m not able to put Configuracaofirebase.getDatabase(). setPersistenceEnabled(true); correctly

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_retiro);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    //INSTANCIANDO OS COMPONENTES
    cardPlacar = (CardView) findViewById(R.id.card_placar);
    btCardapio1 = (Button) findViewById(R.id.bt_dia1_cardapio);
    btCardapio2 = (Button) findViewById(R.id.bt_dia2_cardapio);
    btCardapio3 = (Button) findViewById(R.id.bt_dia3_cardapio);
    tvCardapio = (TextView) findViewById(R.id.tv_cardapio);
    tvCronograma = (TextView) findViewById(R.id.tv_cronograma);
    tvPlacarA = (TextView) findViewById(R.id.tv_placarA);
    tvPlacarB = (TextView) findViewById(R.id.tv_placarB);
    tvAtualizado = (TextView) findViewById(R.id.tv_atualizacao_placar);

    //Adicionando fontes externas
    Typeface fonteDescricao = Typeface.createFromAsset(getAssets(), "fonts/Royalacid.ttf");
    tvCardapio.setTypeface(fonteDescricao);
    tvCronograma.setTypeface(fonteDescricao);

    //Eventos
    btCardapio1.setOnClickListener(this);
    btCardapio2.setOnClickListener(this);
    btCardapio3.setOnClickListener(this);
    cardPlacar.setOnClickListener(this);
    mostrarPLacar();
}

//Atualiza o placar no momento da abertura da tela
private void mostrarPLacar() {
    //Pegando o ano atual
    Date ano = Calendar.getInstance().getTime();
    DateFormat format = new SimpleDateFormat("yyyy");
    String anoRetiro = format.format(ano);

    ConfiguracaoFirebase.getDatabase().setPersistenceEnabled(true);

    queryFirebase = ConfiguracaoFirebase.getFirebaseReference()
            .child("RETIRO")
            .child(anoRetiro)
            .child("PLACAR")
            .orderByChild("atualizacao")
            .limitToLast(1);


    queryFirebase.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot data: dataSnapshot.getChildren()){
                Placar placar = data.getValue(Placar.class);
                tvPlacarA.setText(placar.getPlacarEmanuel());
                tvPlacarB.setText(placar.getPlacarGideoes());
                tvAtualizado.setText("Atualizado em: "+ placar.getAtualizacao());
            }

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Toast.makeText(RetiroActivity.this, "Erro na leitura do banco, contate o admin!", Toast.LENGTH_SHORT).show();
        }
    });
}

In this case the method onCreate calls the function that brings the most updated score, already tried to put setPersistenceEnabled(true) within the class Configuracaofirebase and call via getDatabase, already tried to put in the oncreate method and in both failed, the

1 answer

0


I did some research on the Internet and I can get it right according to the structure of the project I’m building. To solve the problem and enable Firebase offline data persistence I needed to add in the Configuracaofirebase class the following method:

public static FirebaseDatabase getDatabase(){
    if (database == null){
        database = FirebaseDatabase.getInstance();
        database.setPersistenceEnabled(true);
    }
    return database;
}

And with that I make his call in my main Activity of the project, which is never closed because in the others every time I left Activity and came back a crash closed the app, then to solve all the problems I make the call a single time on Mainactivity onCreate in this way:

FirebaseDatabase database = ConfiguracaoFirebase.getDatabase();
  • To complete I put this call on my Main screen, so it is made only once and stops giving crash problems in the app, Thanks !

Browser other questions tagged

You are not signed in. Login or sign up in order to post.