How to enable Firebase persistence offline

I'm having trouble enabling Firebase offline data persistence in my app. The problem is the following, I have an auxiliary class called Configuationofirebase that starts the necessary objects of firebase, to make the queries and save data I use the DatabaseReference or Query, and I would like that when I read the bank it makes those data available 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 which 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 make a query to bring the latest data, and I am not being 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 onCreate method calls the function that brings the most updated score, I have tried to put setPersistenceEnabled (true) inside the ConfiguracaoFirebase class and call via getDatabase, I have tried to put in the method oncreate and in both I did not succeed, the

Author: ramaral, 2017-10-14

1 answers

I did some research on the internet and got 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 leave the activity and came back a crash closed the app, then to solve all the problems I make the call once in the onCreate of MainActivity like this:

FirebaseDatabase database = ConfiguracaoFirebase.getDatabase();
 0
Author: Eduardo Rafael Moraes, 2017-10-15 17:17:25