从Firebase数据库Android中检索空值

时间:2017-02-01 20:40:46

标签: android firebase firebase-realtime-database

我在我的Firebase数据库中按键搜索,但它检索到null并且我不知道原因。

data.getUrl()data.getText()都给我空值。

在调试中,在行

之前
test data = dataSnapshot.getValue(test.class);

它告诉我数据应该检索我正在寻找的内容,但是当该行执行时,它会给我null。

数据库结构:

{
  "images" : {
    "partner " : {
      "text" : "partner",
      "url" : "http://res.cloudinary.com/dg3jylcsw/image/upload/v1483565650/sister_x3lv6j.png"
    },
    "sister" : {
      "text " : "sister",
      "url" : "http://res.cloudinary.com/dg3jylcsw/image/upload/v1483565650/sister_x3lv6j.png"
    }
  }
}

测试类:

package com.example.android.testy;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown=true)
public class test {
    private String text;
    private String url;

    public test() {
        // empty default constructor, necessary for Firebase to be able to deserialize blog posts
    }
    public String getText() {
        return text;
    }

    public String getUrl() {
        return url;
    }
}

主要活动:

package com.example.android.testy;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.Query;
import com.firebase.client.ValueEventListener;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Firebase.setAndroidContext(this);

        Firebase rootRef = new Firebase("https://test-219f8.firebaseio.com/images");
        Query queryRef = rootRef.orderByKey().equalTo("sister");
        queryRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                    test data = dataSnapshot.getValue(test.class);

                    System.out.println(data.getUrl());

            }

            @Override
            public void onCancelled(FirebaseError firebaseError) {
                System.out.println("The read failed: " + firebaseError.getMessage());
            }
        });

    }


}

1 个答案:

答案 0 :(得分:0)

您需要使用addChildEventListener代替addValueEventListener

试试这个:

queryRef.addChildEventListener(new ChildEventListener() {
    public void onChildAdded(DataSnapshot dataSnapshot, String previousKey) {
        test data = dataSnapshot.getValue(test.class);

                    System.out.println(data.getUrl());
    }
    public void onChildChanged(DataSnapshot dataSnapshot, String s) {
    }
    public void onChildRemoved(DataSnapshot dataSnapshot) {
    }
    public void onChildMoved(DataSnapshot dataSnapshot, String s) {
    }
    public void onCancelled(FirebaseError firebaseError) { }
});