我正在检索用户的uid,并以一种方法获取uid,并检索用户的名称和等级,并将其放入列表视图。我希望用户信息显示在列表视图中,但无法正常工作。 这是我的代码:
private FirebaseDatabase database;
private DatabaseReference myRef;
String user_info = "info";
String name = null;
ListView lv;
ArrayList<String> list=new ArrayList<>();
@Override
protected void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.admin_show_students_uid);
lv = (ListView) findViewById(R.id.lv_science_students);
final ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list);
lv.setAdapter(adapter);
lv.setStackFromBottom(true);
TextView display_class_name = (TextView) findViewById(R.id.textView3);
final String post_key = getIntent().getStringExtra("post_key");
database = FirebaseDatabase.getInstance();
myRef = database.getReference("Science").child(post_key).child("Students");
// System.out.println(post_key);
// txt = (TextView) findViewById(R.id.textView3);
display_class_name.setText(post_key);
myRef.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(@NonNull DataSnapshot dataSnapshot, String s) {
name = dataSnapshot.getValue(String.class);
// name = name.trim().toString();
myRef = database.getReference("Users").child(name).child("User_info");
System.out.println(myRef);
// DatabaseReference studentRef = database.getReference("Users").child(name);
list.add(getusersinfo());
//list.add(user_info);
/* myRef.addValueEventListener(new ValueEventListener()) {
@Override
public void onDataChange (DataSnapshot dataSnapshot){
User post = dataSnapshot.getValue(User.class);
// ...
}
@Override
public void onCancelled (DatabaseError error){
}
}*/
// System.out.println(user_info);
//getusersinfo();
// list.add(user_info);
adapter.notifyDataSetChanged();
}
@Override
public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
}
@Override
public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
public String getusersinfo(){
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
//for (DataSnapshot dataSnapshot2 : dataSnapshot.getChildren()) {
User user = dataSnapshot.getValue(User.class);
String email = user.getName();
String grade = user.getGrade();
//String grade = user.getGrade();
//String email = user.getEmail();
// System.out.println(user);
user_info = ("Name " + email + "Grade" + grade);
// System.out.println(user_info);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
System.out.println(user_info);
return user_info;
}
}
getusersinfo方法没有从onDataChange返回更新的user_info变量。 System.out.println(user_info)返回我在类顶部分配的值,而不是在onDataChange中设置的user_info变量;因此,当我运行应用程序时,Listview仅显示声明的user_info的原始值在类的顶部(“信息”)。预先谢谢您...如果您对代码有任何疑问,请告诉我!