使用身份验证用户从Firebase检索数据不会显示在ListView上

时间:2019-02-17 08:26:42

标签: android firebase listview

我想使用身份验证用户从Firebase检索数据。我使用ListView来显示数据。但运行后不会显示。 My firebase structure

public class InfoDisplayActivity extends AppCompatActivity {

    private ListView listViewINFO;
    DatabaseReference databaseReference;
    FirebaseAuth firebaseAuth;
    List<UserInformation> infoList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_info_display);

        listViewINFO = findViewById(R.id.listViewINFO);
        firebaseAuth = FirebaseAuth.getInstance();

        if (firebaseAuth.getCurrentUser() == null){
            finish();
            startActivity(new Intent(this,RegisterActivity.class));
        }
        //FirebaseUser user = firebaseAuth.getCurrentUser();


        infoList = new ArrayList<>();
    }

    @Override
    protected void onStart() {
        super.onStart();
        databaseReference = FirebaseDatabase.getInstance().getReference("User Information");
        FirebaseUser user = firebaseAuth.getCurrentUser();
        String UserID = user.getUid();
        databaseReference.child("User Information").child(UserID).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot INFOSnapshot : dataSnapshot.getChildren()){
                    UserInformation  userInfo = INFOSnapshot.getValue(UserInformation.class);
                    infoList.add(userInfo);
                }
                UserInfoAdapter userInfoAdapter = new UserInfoAdapter(InfoDisplayActivity.this, infoList);
                listViewINFO.setAdapter(userInfoAdapter);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }
}

我遵循YouTube上的this教程。

1 个答案:

答案 0 :(得分:0)

您的代码中的问题是您两次使用User Information引用。声明databaseReference对象时一次:

databaseReference = FirebaseDatabase.getInstance().getReference("User Information");
//                                                                      ^

第二,当您附加侦听器时:

databaseReference.child("User Information").child(UserID).addListenerForSingleValueEvent(/* ... */);
//                              ^

要解决此问题,只需从上面的代码行中删除.child("User Information")

databaseReference.child(UserID).addListenerForSingleValueEvent(/* ... */);