从firebase检索和显示值

时间:2017-05-30 11:56:31

标签: java android firebase

我试图从firebase检索数据并在recyclerview上显示它。我在尝试运行应用程序时遇到错误(下面的错误)。我想知道它是否是导致错误的循环,或者是因为我得到了错误的值。任何人都可以帮我吗?我试图获取存储在我的firebase中的通知消息(" test"," test2")。将在下面显示数据库的图像。

错误

  

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

数据库 enter image description here

NotificationFragment.java

   private void prepareNotification1() {
        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        String userID = user.getUid();
        mRef.child("customers").child(userID).child("Notification").addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                    System.out.println(postSnapshot.getValue());
//                    System.out.println(dataSnapshot.getKey());
//                    Log.d("value", dataSnapshot.getKey());
                    Notification menu = postSnapshot.getValue(Notification.class);
                    notificationList.add(menu);
                }
                mAdapter.notifyDataSetChanged();
                }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

    }

Notification.java

public class Notification {
    private String notification;




    public Notification(){
    }

    public Notification(String notification){
        this.notification = notification;
    }

    public String getNotification() {
        return notification;
    }

    public void setNotification(String notification) {
        this.notification = notification;
    }
}

如果需要,我也可以发布我的适配器代码。

2 个答案:

答案 0 :(得分:1)

您似乎正在尝试将String直接转换为Notification。 Firebase将返回一个可用于创建通知的字符串。

您可以尝试使用以下代码从Firebase中的数据创建通知。

for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
    Notification menu = new Notification(postSnapshot.getValue(String.class));
    notificationList.add(menu);
}

答案 1 :(得分:0)

试试此代码

mRef.child("customers").child(userID).child("Notification").addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {

                Notification menu = postSnapshot.getValue().toString();
                notificationList.add(menu);
            }
            mAdapter.notifyDataSetChanged();
            }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });