After hours of searching for a solution without a result.
(经过数小时的搜索,没有结果。)
I had to ask this question. (我不得不问这个问题。)
The problem is I couldn't set the text view value inside the addListenerForSingleValueEvent() method. (问题是我无法在addListenerForSingleValueEvent()方法内设置文本视图值。)
I successfully get the value that I want to display from the database but the value of the text view does not change. (我成功地从数据库中获取了要显示的值,但文本视图的值未更改。)
I need to understand why and how can I solve the problem. (我需要了解为什么以及如何解决该问题。)
This is my fragment class. (这是我的片段类。)
public class ProfilFragment extends Fragment {
private FirebaseAuth auth;
private FirebaseDatabase database;
private DatabaseReference usersRef;
private TextView firstName, email;
View myView;
public ProfilFragment(){
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
auth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance();
usersRef = database.getReference("Users");
myView= inflater.inflate(R.layout.fragment_profil,container,false);
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("Profile");
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_profil, null);
firstName = root.findViewById(R.id.profileFirstNameTextView);
email = root.findViewById(R.id.profileEmailTextView);
FirebaseUser firebaseUser = auth.getCurrentUser();
email.setText("bla bla bla");
if(firebaseUser != null){
final String userId = firebaseUser.getUid();
usersRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChild(userId)){
User user = dataSnapshot.child(userId).getValue(User.class);
Log.d(TAG, "user: " + user.getFirstName());
showTextViews(user);
} else{
Toast.makeText(getActivity(), "Couldn't find the user!!",
Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
} else {
Toast.makeText(getActivity(), "Problem in getting data from Database",
Toast.LENGTH_SHORT).show();
}
return myView;
}
private void showTextViews(User user) {
Log.d(TAG, "showTextViews: we entered this function");
firstName.setText(user.getFirstName());
email.setText(user.getEmail());
}
the two logs are rendered so the logic should be right.
(呈现了两个日志,因此逻辑应该正确。)
Even when I set the text view to "bla bla bla" outside the method it didn't work. (即使在该方法之外将文本视图设置为“ bla bla bla”,它也不起作用。)
ask by chiheb translate from so 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…