It is given: Application working with firebase.

Problem: The application crashes when you first start if there is no Internet ( because it does not have time to cache the database from the Internet ). Let me explain in more detail the application is implemented so that when you first start an anonymous user is created in the database and if you turn off the Internet after that, the application works without problems, but if this is the first start and no Internet falls with an NPE error ( because user null, as so it is clear, no Internet can register anonymously )

Question: How can you implement support for offline mode when you first start the application and certainly the absence of the Internet

Additionally: I did everything as written in the guides.

FirebaseDatabase.getInstance().setPersistenceEnabled(true); DatabaseReference scoresRef = FirebaseDatabase.getInstance().getReference("scores"); scoresRef.keepSynced(true); 

    1 answer 1

    Solved the problem as follows:

    1. When you first start without the Internet, user is null ( because there is no Internet ), I create my local user

       @NonNull private String getUid() { String userID; if (user == null) { userID = UUID.randomUUID().toString(); } else { userID = user.getUid(); } Log.d(LOG_TAG, "userID = " + userID); return userID; } 
    2. On subsequent launches of the application, I check if there is internet and the first launch was without internet, then anonymous authorization and copying of local data to the database takes place, after that I delete the old database by copying all the data from it into the new one

       public void moveFirebaseRecord(final DatabaseReference fromPath, final DatabaseReference toPath) { fromPath.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { toPath.setValue(dataSnapshot.getValue(), new DatabaseReference.CompletionListener() { @Override public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) { if (databaseError != null) { Log.d(LOG_TAG, "moveFirebaseRecord() failed. firebaseError = " + databaseError); } else { fromPath.removeValue();// deleteAll from oldDB Log.d(LOG_TAG, "moveFirebaseRecord() Great success!"); } } }); } @Override public void onCancelled(DatabaseError databaseError) { } }); 

      }