Reputation: 37
I am unable to add any listener after the end of the onCanelled Listener Actually, I want to do some task after getting data from the snapshot for which I need onSuccessListener and I am unable to add that
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
Upvotes: 0
Views: 593
Reputation: 598728
The addListenerForSingleValueEvent
method doesn't return a Task
, so you can't attach a success listener to it.
If you need to run some code after the data has been loaded, put that code into the onDataChange
method. If the code must also run if the listener gets rejected by the server-side security rules, also add/call the same code from onCancelled
.
So something like:
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 ...
}
});
Upvotes: 1