Reputation: 81
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. 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.
Upvotes: 0
Views: 92
Reputation: 15423
Why you inflate
same view twice? Try to use myView
instead of root
to find out child views like below:
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
....
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 = myView.findViewById(R.id.profileFirstNameTextView);
email = myView.findViewById(R.id.profileEmailTextView);
....
return myView;
}
Upvotes: 1