将Child Fires数据库的Childs获取到Listview

时间:2018-04-05 08:42:46

标签: android firebase listview firebase-realtime-database

我正试图从listview上的firebase数据库中获取孩子的孩子。 firebase结构是这样的:Firebase database。 当我运行以下代码时,我的应用程序在启动该活动时崩溃。 我的代码如下:

    String TripIDD = intent.getStringExtra(AvailableRides.EXTRA_MESSAGE9);

    final DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
    final DatabaseReference tripsRef = rootRef.child("Trips").child(TripIDD);
    ValueEventListener valueEventListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            List<String> passengers = new ArrayList<String>();
            ArrayAdapter adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, passengers);
            ListView Passengers = (ListView) findViewById(R.id.passengerslist);
            for (final DataSnapshot ds : dataSnapshot.getChildren()) {
                String user = ds.child("Passengers on the ride").getValue(String.class);
                passengers.add(user);
                Passengers.setAdapter(adapter);
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    };
}

2 个答案:

答案 0 :(得分:1)

对于基本写入操作,您可以使用setValue()将数据保存到指定的引用,替换该路径上的任何现有数据。您可以使用此方法: 传递与可用JSON类型对应的类型,如下所示: 串 长 双 布尔 地图 名单 传递自定义Java对象,如果定义它的类具有不带参数的默认构造函数,并且具有要分配的属性的公共getter。 例如,如果您的应用程序具有基本用户配置文件,则您的User对象可能如下所示:

public class User {
    public String username;
    public String email;
    public User() {
        // Default constructor required for calls to DataSnapshot.getValue(User.class)
    }
    public User(String username, String email) {
        this.username = username;
        this.email = email;
    }
}

您可以使用setValue()添加用户,如下所示:

private void writeNewUser(String userId, String name, String email) {
    User user = new User(name, email);
    mDatabase.child("users").child(userId).setValue(user);
}

如下所示阅读

private FirebaseAuth mAuth;
    private DatabaseReference mUsersDBRef;
    private RecyclerView mRecyclerView;
    private RecyclerView.LayoutManager mLayoutManager;
    private UsersAdapter adapter;
    private List<User> mUsersList = new ArrayList<>();

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

        //assign firebase auth
        mAuth = FirebaseAuth.getInstance();
        mUsersDBRef = FirebaseDatabase.getInstance().getReference().child("Users");
        //initialize the recyclerview variables
        mRecyclerView = (RecyclerView)findViewById(R.id.usersRecyclerView);
        mRecyclerView.setHasFixedSize(true);
        // use a linear layout manager
        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);
    }
    private void queryUsersAndAddthemToList(){
            mUsersDBRef.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    if(dataSnapshot.getChildrenCount() > 0){
                        for(DataSnapshot snap: dataSnapshot.getChildren()){
                            User user = snap.getValue(User.class);
                            //if not current user, as we do not want to show ourselves then chat with ourselves lol
                            try {
                                if(!user.getUserId().equals(mAuth.getCurrentUser().getUid())){
                                    mUsersList.add(user);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    /**populate listview**/
                    adapter = new UsersAdapter(mUsersList, ChatUsersActivity.this);
        mRecyclerView.setAdapter(adapter);
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
        }

答案 1 :(得分:0)

要解决此问题,您需要两次查询数据库:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference tripsRef = rootRef.child("Trips");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String key = ds.getKey();

            DatabaseReference keyRef = tripsRef.child(key).child("Passengers on the ride");
            ValueEventListener eventListener = new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    for(DataSnapshot dSnapshot : dataSnapshot.getChildren()) {
                        String passenger = dSnapshot.getValue(String.class);
                        Log.d("TAG", passenger);
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {}
            };
            keyRef.addListenerForSingleValueEvent(eventListener);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
tripsRef.addListenerForSingleValueEvent(valueEventListener);

输出将是所有旅程中Passengers on the ride节点内的所有乘客。

如果您只想获得一次旅行的乘客,请使用以下代码:

String TripIDD = intent.getStringExtra(AvailableRides.EXTRA_MESSAGE9);
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = rootRef.child("Trips").child(TripIDD).child("Passengers on the ride");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String passenger = ds.getValue(String.class);
            Log.d("TAG", passenger);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
ref.addListenerForSingleValueEvent(valueEventListener);

其中TripIDD是您想要获得的特定旅行的ID(例如-L8wwgt3FeQjzAUeTJon)。