2016-11-02 42 views
0

我新的火力点,我试图在实现实时数据库机器人。我可以写信给DB成功地但是当我尝试从数据库读取,我得到com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.softworld.crib.models.Usercom.google.firebase.database.DatabaseException:无法转换java.lang.String类型的对象键入com.softworld.crib.models.User

Here is my DB on firebase

我这是怎么发布,并从DB

DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference("myUsers"); 
String userId = dbRef.push().getKey(); 

     User user = new User("My New Name","[email protected]",loggedInUser.getPersonPhoto()); 
//how I post to db 
     dbRef.child(userId).setValue(user); 
//how I read from db 
dbRef.child(userId).addValueEventListener(new ValueEventListener() { 
      @Override 
      public void onDataChange(DataSnapshot dataSnapshot) { 
       // This method is called once with the initial value and again 
       // whenever data at this location is updated. 
       List users = new ArrayList<>(); 

       for (DataSnapshot noteDataSnapshot : dataSnapshot.getChildren()) { 
        User user = noteDataSnapshot.getValue(User.class); 
        Toast.makeText(MainActivity.this, user.getPersonEmail(), Toast.LENGTH_LONG).show(); 
        users.add(user); 
       } 

       //Log.d(TAG, "Value is: " + value); 
      } 

      @Override 
      public void onCancelled(DatabaseError error) { 
       // Failed to read value 
       //Log.w(TAG, "Failed to read value.", error.toException()); 
      } 
     }); 

我的User类阅读看起来是这样的

public class User { 
    String personName,personEmail; 
    Uri personPhoto; 

    public User() { 
    } 

    public User(String personName, String personEmail, Uri personPhoto) { 
     this.personName = personName; 
     this.personEmail = personEmail; 
     this.personPhoto = personPhoto; 
    } 

    public String getPersonName() { 
     return personName; 
    } 

    public void setPersonName(String personName) { 
     this.personName = personName; 
    } 

    public String getPersonEmail() { 
     return personEmail; 
    } 

    public void setPersonEmail(String personEmail) { 
     this.personEmail = personEmail; 
    } 

    public Uri getPersonPhoto() { 
     return personPhoto; 
    } 

    public void setPersonPhoto(Uri personPhoto) { 
     this.personPhoto = personPhoto; 
    } 
} 

回答

2

我想你应该改变

dbRef.child(userId).addValueEventListener(new ValueEventListener() { 

dbRef.addValueEventListener(new ValueEventListener() { 

https://www.firebase.com/docs/android/guide/retrieving-data.html

解释或者,如果你真的想只得到一个事件这个特定userId的DataSnapshot你得到的是可能已经你要找的用户,因此在

中使用 .getChildren()
for (DataSnapshot noteDataSnapshot : dataSnapshot.getChildren()) { 

可能是不必要的。

+0

我已经改变了和转换错误dissapeared。然而,现在我越来越java.lang.InstantiationException:不能实例化抽象类android.net.Uri –

+0

如果不是在同一个地方,这是另一个问题。也许你应该记录如何调试应用程序(循序渐进,日志,读取栈跟踪......) –

+0

correct @Orabîg我发现问题在别的地方。但你的解决方案更改为dbRef.addValueEventListener(新的ValueEventListener(){解决了我的问题。 –

相关问题