Android 无法设置textView值
在数小时的搜索后,没有结果。我不得不问这个问题。 问题是我无法在addListenerForSingleValueEvent方法内设置文本视图值。我成功地从数据库中获取了要显示的值,但文本视图的值没有更改。我需要了解为什么以及如何解决这个问题。这是我的片段类Android 无法设置textView值,android,firebase,android-layout,firebase-realtime-database,Android,Firebase,Android Layout,Firebase Realtime Database,在数小时的搜索后,没有结果。我不得不问这个问题。 问题是我无法在addListenerForSingleValueEvent方法内设置文本视图值。我成功地从数据库中获取了要显示的值,但文本视图的值没有更改。我需要了解为什么以及如何解决这个问题。这是我的片段类 public class ProfilFragment extends Fragment { private FirebaseAuth auth; private FirebaseDatabase database; private D
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());
}
这两个日志被呈现,因此逻辑应该是正确的。即使我在方法之外将文本视图设置为blablabla,它也不起作用 为什么要将同一视图膨胀两次?尝试使用myView而不是root来查找子视图,如下所示:
@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;
}
添加数据库结构。尝试使用myView而不是root。为什么要将同一个视图放大两次?这解决了问题,谢谢。如何将此问题标记为已回答?请检查我的答案。接受它,并投票表决。谢谢