0
我新的火力點,我試圖在實現實時數據庫機器人。我可以寫信給DB成功地但是當我嘗試從數據庫讀取,我得到com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.softworld.crib.models.User
com.google.firebase.database.DatabaseException:無法轉換java.lang.String類型的對象鍵入com.softworld.crib.models.User
我這是怎麼發佈,並從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;
}
}
我已經改變了和轉換錯誤dissapeared。然而,現在我越來越java.lang.InstantiationException:不能實例化抽象類android.net.Uri –
如果不是在同一個地方,這是另一個問題。也許你應該記錄如何調試應用程序(循序漸進,日誌,讀取棧跟蹤......) –
correct @Orabîg我發現問題在別的地方。但你的解決方案更改爲dbRef.addValueEventListener(新的ValueEventListener(){解決了我的問題。 –