简体   繁体   English

如何在片段 class 的文本视图中显示来自 firebase 的值

[英]how to display a value from firebase in a text view in a fragment class

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.我无法获得从 firebase 中检索值并使用片段 class 中的文本视图显示它的逻辑。基本上,文本应该是 go“嗨,”+ 我应该得到的 firebase 中的值。 but i feel like my logic does not suffice the code i have here?但我觉得我的逻辑不足以满足我这里的代码? can someone help?有人可以帮忙吗?

This is the fragment class:这是片段 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"
       />

As soon as you call return in a function, it ends and the code after that return statement doesn't execute.一旦您在 function 中调用return ,它就会结束并且return语句之后的代码不会执行。 So looking at your onCreateView :所以看看你的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(); 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();你会想要移动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:声明到 function 的末尾,以便代码的 rest 执行 - onCreateView仅在完成所有操作后才完成:

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.还需要注意的一件事是,一旦数据加载完成,就会异步调用onDataChange So the code you have inside that method will also run well after the onCreateView has completed.因此,您在该方法中拥有的代码在onCreateView完成后也将运行良好。

To learn more about this, see getContactsFromFirebase() method return an empty list .要了解更多信息,请参阅getContactsFromFirebase() 方法返回一个空列表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 SwiftUI 和 MVVM:如何在 View 中显示来自 Firebase/Firestore 的数据? - SwiftUI and MVVM: How to display data from Firebase/Firestore in View? 如何从片段中的 Firebase 实时数据库中检索数据? - How to Retrieve Data from Firebase Realtime Database in Fragment? 如何从 firebase 存储下载和显示图像 - How to download and display images from firebase storage 如何从实时数据库[Firebase]中读取和显示? - How to read and display from realtime database [Firebase]? 如何显示来自 firebase 的当前用户数据? - How to display current User data from firebase? 如何显示来自 firebase 的图像? - how can i display image from firebase? 如何在flutter中显示firebase的数据? - How to display the data from firebase in flutter? 显示子项内部特定值的所有内容 - Xamarin Firebase - Display everything from specific value inside child - Xamarin Firebase 如何通过 Firebase ML 套件文本识别扫描七段显示器? - How To Scan a Seven Segment Display by Firebase ML kit Text Recognition? 如何使用 Firebase 和 Kotlin 在文本(Jetpack Compose)中显示当前用户名? - How to display current username in Text (Jetpack Compose) using Firebase and Kotlin?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM