com.google.firebase.database.DatabaseException:无法将java.lang.String类型的对象转换为com.softworld.crib.models.User类型

时间:2016-11-02 08:34:47

标签: java android firebase firebase-realtime-database

我是firebase的新手,我正在尝试在android上实现实时数据库。我可以成功地写入数据库但是当我尝试从数据库中读取时,我得到 Dim opdragdeleteNuloesskattings As New SqlCommand konneksie.ConnectionString = "Data Source=GIDEON-E-LAPTOP\SQLEXPRESS2014;Initial Catalog=SkeduleringDatabasis;Integrated Security=True" konneksie.Open() opdragdeleteNuloesskattings.Connection = konneksie opdragdeleteNuloesskattings.CommandText = " DELETE " & _ " FROM Oesskattings " & _ " WHERE ton_skat_tot = 0 "

Here is my DB on firebase

这是我从DB发布和阅读的方式

com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.softworld.crib.models.User

我的User类看起来像这样

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

        User user = new User("My New Name","mynewemail@gmail.com",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());
            }
        });

1 个答案:

答案 0 :(得分:2)

我认为你应该改变

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

  dbRef.addValueEventListener(new ValueEventListener() {

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

中所述

或者,如果您真的只希望获得此特定userId的活动,则您获得的DataSnapshot可能已经是您正在寻找的用户,因此请使用{/ 1}}

.getChildren()

可能是不必要的。