如何在firebase实时数据库中访问子值

时间:2016-09-13 14:51:12

标签: android firebase-realtime-database

我有一个存储用户地址的实时firebase数据库。我想获取值并将它们分配给android布局中的textviews。我试过访问这样的数据:

String city = (mDatabase.getDatabase().getReference().child(user_data.getString("uidkey", null)).child("city")).toString();
        _cityText.setText(city);

但是这只给了我街道的firebase网址而不是实际值。我该如何检索这些数据?

This is how the database looks like.

public void onStart(){
        super.onStart();
        final SharedPreferences user_data = getSharedPreferences("PESASEND_PREFS", Context.MODE_PRIVATE);

        mDatabase.child(user_data.getString("uidkey", null)).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                Address address = dataSnapshot.getValue(Address.class);
              //  address.getCity();

                _state_province_Text.setText(address.getStreet());
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

    }

public class Address {

    public String street;
    public String city;
    public String state;
    public String zip_postal_code;
    public String country;

    public Address (){};

    public Address(String street, String city, String state, String zip_postal_code, String country ){
        this.street = street;
        this.city = city;
        this.state = state;
        this.zip_postal_code = zip_postal_code;
        this.country = country;
    }

    public String getStreet (){return street;}
    public String getCity (){return city;}
    public String getState (){return state;}
    public String getZipPostalCode (){return zip_postal_code;}
    public String getCountry (){return country;}

}

1 个答案:

答案 0 :(得分:0)

在firebase中获取数据的推荐方法是创建表示要从数据库中提取的对象的类,确保该类的所有成员完全匹配您想要提取的数据的键(例如,你将拥有一个包含5个字符串,城市,国家,州,街道,zip_postal_code的对象,并确保所有这些对象都有setter和getter(只是自动生成这些)

然后,您可以为数据库引用添加一个侦听器,如下所示:

mDatabase.child("Addresses").child(user_data.getString("uidkey", null)).addListenerForSingleValueEvent(
        new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                // Get the address object
                Address address = dataSnapshot.getValue(Address.class);
                // get the string here, using address.getCity() or whatever you called the getter

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });

您还可以使用相同的地址类向firebase添加新的地址对象。

此外,如果您正在填充列表视图,如果您使用firebaseListAdapter

,这可以更简单,更清晰