Search code examples
javafirebasefirebase-realtime-databasefinalanonymous-class

Firebase Callback Interface needs to be declared final?


Following is the code and on one of the line, android studio is asking me to declare as final

      public void getFullName(GetFullNameCallback getFullNameCallback) { usersRef.child(mAuth.getUid()).child("fN").addListenerForSingleValueEvent(new ValueEventListener() {
          @Override
          public void onDataChange(DataSnapshot dataSnapshot) {

            getFullNameCallback.onCallback(dataSnapshot.getValue().toString());
          }

          @Override
          public void onCancelled(@NonNull DatabaseError databaseError) {}
        });
      }


      private interface GetFullNameCallback {
        void onCallback(String fullName);
      }

At the getFullNameCallback.onCallback() in onDataChange, it is underlined red as it says getFullNameCallback should be declared final but according to this answer, it is just fine??


Solution

  • As explained in Why are only final variables accessible in anonymous class?, only final variables are accessible inside an anonymous class.

    In your code you receive getFullNameCallback as parameter in getFullName method (it is not a local variable inside the code which creates a new instance of an ValueEventListener).

    Moreover you use it (getFullNameCallback) inside the anonymous class ValueEventListener, so, getFullNameCallback must be final in order to be used (again, it is explained why in the linked post).