Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase: Database write before sign in

I am using Firebase in my android app. My purpose is that the a user of the application should be able to write data to the database but I don't want the user to sign up so i am using anonymous sign in.

I have a form that the user can submit and will be committed to database. At the time of submitting it is possible that the anonymous sign-in may not have been done. Is it possible in Firebase that I call the write instruction to the database and it is written locally and commits the moment the user is signed in anonymously?

I know that Firebase does provide offline capabilities. But I assume if i were to call write database before signing in, it would give me an error.

like image 976
Bember Pish Avatar asked Nov 08 '22 06:11

Bember Pish


1 Answers

I had the same concern when developing an application. If a user had their phone in airplane mode or were offline at first launch, it was possible they could reach a point where they needed to save data before the anonymous authentication completed successfully.

A workaround is to create an "unauthenticated" tree in your database that is writable by anyone, but readable only once authenticated. When the user is authenticated you can copy the data to an appropriate location and delete any data written in the unauthenticated area. You can queue up data to be written and Firebase will automatically write when the user is online.

The trick is to get a push id in the unauthenticated tree that you will use as a temporary user id. This value should be persisted locally using SharedPreferences or another method of your choosing.

    db = FirebaseDatabase.getInstance();
    db.setPersistenceEnabled(true);

    dbRef = db.getReference();

    // This key should be saved on the user's device until authenticated
    String key = dbRef.child("unauthenticated").push().getKey();

    // Write some data 
    dbRef.child("unauthenticated").child(key)
         .child("somedata").setValue("testing");

Any writes that you make to this child will be persisted as soon as the network connection becomes available. Attaching a listener to this temporary key might look something like below...

    dbRef.child("unauthenticated").child(key).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Log.d("DB", "Got value from database: " + dataSnapshot.child("somedata").getValue());

            if(FirebaseAuth.getInstance().getCurrentUser() != null) {
                /** If user is authenticated, move data to authenticated location **/
            }
        }
        @Override public void onCancelled(DatabaseError databaseError) {}
    });
like image 110
Victor Rendina Avatar answered Nov 15 '22 04:11

Victor Rendina