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"
/>