How to Enable Firebase Offline Persistence

0

I'm having trouble enabling persistence of firebase offline data in my app. The problem is the following, I have an auxiliary class called ConfigurationFirebase that starts the required objects from the firebase, to make the queries and save data I use the DatabaseReference or Query, and I would like that when reading the database it would make those data available offline, 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 template 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 make a query to bring the latest data, and I'm not able to put ConfigurationFirebase.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 up-to-date scorecard, I've already tried putting setPersistenceEnabled (true) inside the class ConfigFirebase and calling via getDatabase, I tried to put it in the oncreate method and both did not succeed, p>     

asked by anonymous 14.10.2017 / 22:59

1 answer

0

I did some research on the internet and was able to get it right according to the structure of the project I'm building. To solve the problem and activate Firebase offline data persistence, I had to add the following method to the ConfiguringFirebase class:

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

And with that I make the call of it in my main activity of the project, which is never closed because in the others every time I quit the activity and crash closed the app, then to solve all the problems I do call a single time in the onCreate of MainActivity like this:

FirebaseDatabase database = ConfiguracaoFirebase.getDatabase();
    
15.10.2017 / 19:17