Android Firebase addListenerForSingleValueEvent传递值

时间:2018-12-06 05:22:10

标签: android firebase firebase-realtime-database

我在片段中有一个按钮,单击该按钮应检查firebase db中是否存在数据。下面是一个单独的类文件中的函数,该文件将在异步任务中单击按钮时调用。

如何从addListenerForSingleValueEvent返回布尔值true / false到片段异步任务?

void checkDataExists(final String mobile){
DatabaseReference fireDBRef = FirebaseDatabase.getInstance().getReference(context.getString(R.string.app_name);

fireDBRef.addListenerForSingleValueEvent(new ValueEventListener() {
                 @Override
                 public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                 String mob = 
     String.valueOf(dataSnapshot.child(context.getString(R.string.tracked_mobile))
                             .getValue());
                             
                //compare the strings mobile 
                 boolean match = mobile.equals(mob);

                // return match value to fragment to update the view.
                }

                 @Override
                 public void onCancelled(@NonNull DatabaseError databaseError) {
                     Log.w(TAG + "/checkDataExists","Data read from DB failed: " + databaseError.getMessage());
                 }
             });
         }

1 个答案:

答案 0 :(得分:1)

我也有这样的情况,我创建了自己的回调,如:

public interface IMyCallback {
    void onSuccess(boolean isExist);
    void onFailure(String error);
}

现在,当我调用函数checkDataExists时,它看起来像:

checkDataExists(mobile, new ISingUpCallback() {
                @Override
                public void onSuccess(boolean isExist) {

                }

                @Override
                public void onFailure(String error) {

                }
            });

在检查中,您需要进行如下更改:

    void checkDataExists(final String mobile, final IMyCallback callback){
    DatabaseReference fireDBRef = FirebaseDatabase.getInstance().getReference(context.getString(R.string.app_name);

    fireDBRef.addListenerForSingleValueEvent(new ValueEventListener() {
                     @Override
                     public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                     String mob = 
         String.valueOf(dataSnapshot.child(context.getString(R.string.tracked_mobile))
                                 .getValue());

                    //compare the strings mobile 
                     boolean match = mobile.equals(mob);

                    // return match value to fragment to update the view.
                    callback.onSuccess(match);
                    }

                     @Override
                     public void onCancelled(@NonNull DatabaseError databaseError) {
                         callback.onFailure(databaseError.getMessage());
                     }
                 });
             }
相关问题