从Firebase

时间:2016-12-15 04:21:59

标签: android firebase firebase-realtime-database

我正在尝试创建一个Android应用,我使用Firebase存储信息列表。我能够在没有问题的情况下将信息存储在实时数据库中,但我目前遇到的问题是试图找出在添加新内容时如何检索列表。

当我在列表中添加,更改或删除值时,不会调用childEventListener个。

FirebaseDatabase database;
DatabaseReference toDatabase;

...

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

        hideAvatar = (Button) findViewById(R.id.hideAvatar);

        database = FirebaseDatabase.getInstance();
        toDatabase = database.getReference("jsierra");

        ...

        hideAvatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                 ...

                getCurrentLocation();
                currentCoordinates = new LatLng(latitude, longitude);
                data store = new data(currentCoordinates);

                toDatabase.push().setValue(store);

                map.addMarker(new MarkerOptions().position(currentCoordinates));
            }
        });
    }

protected void onStart() {
        apiClient.connect();
        super.onStart();

        DatabaseReference test = toDatabase.child("jsierra");

        test.addChildEventListener(new ChildEventListener() {

            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                Toast.makeText(getBaseContext(), "Child Added", Toast.LENGTH_LONG).show();
                givenData = dataSnapshot.getValue(data.class);
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {
                givenData = dataSnapshot.getValue(data.class);
                Toast.makeText(getBaseContext(), "Child Changed", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {
                givenData = dataSnapshot.getValue(data.class);
                Toast.makeText(getBaseContext(), "Child Removed", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {
                givenData = dataSnapshot.getValue(data.class);
                Toast.makeText(getBaseContext(), "Child Moved", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Toast.makeText(getBaseContext(), "Failed", Toast.LENGTH_LONG).show();
            }
        });
    }

1 个答案:

答案 0 :(得分:1)

您的test引用不正确。变化:

DatabaseReference test = toDatabase.child("jsierra");

为:

DatabaseReference test = database.getReference("jsierra");