从Android中的firebase获取数据

时间:2017-04-18 18:35:18

标签: android firebase firebase-realtime-database

  

无法获取它提供的数据“尝试调用虚方法'java.lang.String java.lang.String.toString()”。无法找到任何解决方案请帮忙。

守则

    public class AdminUser extends AppCompatActivity {
    private TextView tv1,tv2;
   private DatabaseReference mDatabase;
    private FirebaseAuth auth;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_admin_user);

        auth = FirebaseAuth.getInstance();
        String username=FirebaseAuth.getInstance().getCurrentUser().getUid();
        mDatabase= FirebaseDatabase.getInstance().getReference().child(username);
        tv1=(TextView)findViewById(R.id.textView6);
        tv2=(TextView)findViewById(R.id.textView8);


       mDatabase.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
           // String name=dataSnapshot.getValue().toString();
                String name=dataSnapshot.child("name").getValue(String.class).toString() ;
                String address=dataSnapshot.child("address").getValue(String.class).toString();
                tv1.setText(name);
                tv2.setText(address);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }
}

1 个答案:

答案 0 :(得分:0)

这2行:

String name=dataSnapshot.child("name").getValue(String.class).toString() ;
String address=dataSnapshot.child("address").getValue(String.class).toString();

导致您的问题,请访问Firebase文档并阅读有关如何从此处从实时数据库中读取数据的信息

https://firebase.google.com/docs/database/android/read-and-write

修改 为了给您一个特定于您的问题的示例,首先您需要创建一个Plain Old Java Object(POJO)类来表示您在数据库中拥有的数据,例如。

public class User {
private String name;
private String address;

public User() {
    //Empty constructor required by firebase 
    // serialize the data retrieved and convert
    // it to an object of this class
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getAddress() {
    return address;
}

public void setAddress(String address) {
    this.address = address;
}
}

然后在你的valueEventListener中你可以做这样的事情

      mDatabase.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
           //Serialize your retrieved data to a User object
            User user = dataSnapshot.getValue(User.class);
            //Now you have an object of the User class and can use its getters like this
            tv1.setText(user.getName());
            tv2.setText(user.getAddress());
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

希望这有帮助