I wanted to count app visits whenever any user open the app. I have done following code which is working successfully only when INTERNET IS ON
I have used FirebaseDatabase.getInstance().setPersistenceEnabled(true);
for storing data offline and also used myRef.keepSynced(true);
to keep syncing.
Here is the code:
// COUNTER PART
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("counter");
myRef.keepSynced(true);
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
Log.i("FB", "Snapshot: " + dataSnapshot);
long val = (long) dataSnapshot.getValue() + 1;
myRef.setValue(val);
mainBinding.contentLayout.textViewCounterVisits.setVisibility(View.VISIBLE);
mainBinding.contentLayout.textViewCounterVisits.setText(getString(R.string.total_visits, val));
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Log.e("FB", "Error: " + error);
}
});
PROBLEM:
When I open the app offline for multiple times its counting offline. When I turned on the Internet, It's just syncing with updated data but I wanted to update count by adding new counts.
For example:
Count is 105
App 1 - Opening for 10 times (offline)
App 2 - Opening for 15 times (online)
Now count is 120
App 1 goes online and opening app and count is updating 121.
I think it should be 131 if we count all.