0

I can't get the logic of retrieving a value from firebase and displaying it using a text view in a fragment class. Basically the text should go "hi! " + the value from the firebase that i should get, but i feel like my logic does not suffice the code i have here. can someone help?

This is the fragment class:

public class HomeFragment extends Fragment {
    FragmentHomeBinding binding;
    FirebaseAuth auth;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragmentHomeBinding.inflate(inflater, container, false);
        return binding.getRoot();

        auth = FirebaseAuth.getInstance(); 
        DatabaseReference mRef = FirebaseDatabase.getInstance().getReference("users");
        mRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                String id = auth.getCurrentUser().getUid();
                if (snapshot.child(id).exists()) {
                    UserHelperClass userHelper = snapshot.child(id).getValue(UserHelperClass.class);
                    binding.tvGetUser.setText("Hi, " + userHelper.getUname() + "!");
                }
            }
            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                Toast.makeText(getActivity(), "Something wrong happened", Toast.LENGTH_SHORT).show();
            }
            });
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
    @Override
    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        checkIfLoggedIn();
        binding.userBtn.setOnClickListener(view1 -> startActivity(new Intent(getActivity(), UserAccountActivity.class)));
    }
    private void checkIfLoggedIn() {
        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        if (user == null) {
            startActivity(new Intent(getActivity(), StartupActivity.class));
            requireActivity().finish();
        }
    }
}

Error here, says unreachable statement

    auth = FirebaseAuth.getInstance(); 

This is the code for the text view

 <TextView
        android:id="@+id/tvGetUser"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="24dp"
        android:fontFamily="@font/futuramediumitalic"
        android:textAlignment="center"
        android:textColor="#3A3B3C"
        android:textSize="18sp"
        android:textStyle="bold"
       />
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

1 Answers1

0

As soon as you call return in a function, it ends and the code after that return statement doesn't execute. So looking at your onCreateView:

public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    binding = FragmentHomeBinding.inflate(inflater, container, false);
    return binding.getRoot();

    auth = FirebaseAuth.getInstance(); 
    DatabaseReference mRef = FirebaseDatabase.getInstance().getReference("users");
    mRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            String id = auth.getCurrentUser().getUid();
            if (snapshot.child(id).exists()) {
                UserHelperClass userHelper = snapshot.child(id).getValue(UserHelperClass.class);
                binding.tvGetUser.setText("Hi, " + userHelper.getUname() + "!");
            }
        }
        @Override
        public void onCancelled(@NonNull DatabaseError error) {
            Toast.makeText(getActivity(), "Something wrong happened", Toast.LENGTH_SHORT).show();
        }
    });
}

None of the code after return binding.getRoot(); executes, and indeed you get a warning from the compiler that it is unreachable.

You'll want to move the return binding.getRoot(); statement to the end of the function, so that the rest of the code executes - and the onCreateView only finishes once all that is done:

public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    binding = FragmentHomeBinding.inflate(inflater, container, false);

    auth = FirebaseAuth.getInstance(); 
    DatabaseReference mRef = FirebaseDatabase.getInstance().getReference("users");
    mRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            String id = auth.getCurrentUser().getUid();
            if (snapshot.child(id).exists()) {
                UserHelperClass userHelper = snapshot.child(id).getValue(UserHelperClass.class);
                binding.tvGetUser.setText("Hi, " + userHelper.getUname() + "!");
            }
        }
        @Override
        public void onCancelled(@NonNull DatabaseError error) {
            Toast.makeText(getActivity(), "Something wrong happened", Toast.LENGTH_SHORT).show();
        }
    });

    return binding.getRoot(); // 
}

One thing to also be aware of is that onDataChange is called asynchronously, once the loading of the data has completed. So the code you have inside that method will also run well after the onCreateView has completed.

To learn more about this, see getContactsFromFirebase() method return an empty list.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807