无法在片段上应用addOnSuccessListener

时间:2018-11-25 03:24:33

标签: android firebase firebase-realtime-database

在onCanelled侦听器结束后,我无法添加任何侦听器 实际上,我想从需要onSuccessListener的快照中获取数据后执行一些任务,而我无法添加

public UserFragment() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view =  inflater.inflate(R.layout.fragment_user, container, false);


    myUserDataList = new ArrayList<>();

    userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
    databaseReference = FirebaseDatabase.getInstance().getReference("/Users/");


    databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren())
            {
                if (Objects.equals(dataSnapshot1.getKey(), userId))
                {
                    MyUserData myUserData = dataSnapshot1.getValue(MyUserData.class);
                    myUserDataList.add(myUserData);
                }
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    }); // Problem over here

1 个答案:

答案 0 :(得分:0)

addListenerForSingleValueEvent方法不会返回Task,因此您无法将成功的侦听器附加到该方法。

如果在数据加载后需要运行一些代码,则将该代码放入onDataChange方法中。如果在服务器端安全规则拒绝了侦听器的情况下也必须运行该代码,则还可以从onCancelled添加/调用相同的代码。

类似这样:

databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren())
        {
            if (Objects.equals(dataSnapshot1.getKey(), userId))
            {
                MyUserData myUserData = dataSnapshot1.getValue(MyUserData.class);
                myUserDataList.add(myUserData);
            }
        }
        onResponseReceived();
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.w(TAG, "Error listening for data: "+databaseError.toString());
        onResponseReceived();
    }

    private void onResponseReceived() {
      ... do what you need to do here ...
    }
});