繁体   English   中英

Android-将带有Firebase功能的侦听器置于类之外

[英]Android - Keep Listener with Firebase function out of the class

我想用MVC编写我的应用程序。 问题是我是Android的新手,并且如果函数不在主类之外,我也不知道如何使用listener / callback

public void addNewUser(String firstname, String lastname, String email, Integer gender, String uid, String profileImageUrl){

        Map<String, Object> data = new HashMap<>();
        data.put("firstname", firstname);
        data.put("lastname", lastname);
        data.put("email", email);
        data.put("gender", gender);
        data.put("boxId", "independent");
        data.put("notificationsEnabled", true);
        data.put("profileImageUrl", profileImageUrl);

        mFirebaseFirestore.collection("usersP").add(data)
                .addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
                    @Override
                    public void onSuccess(DocumentReference documentReference) {
                        mProgressBar.setVisibility(View.GONE);

                        mIRegisterActivity.inflateFragment("Register Box", mHashMap);
                        Log.d(TAG, "DocumentSnapshot written with ID: " + documentReference.getId());
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Log.d(TAG, "Error adding document", e);
                    }
                });

    }

我想在另一个Java类中使用此函数。 但是,如果我这样做,我不知道如何仅在函数完成执行后仍然可以启动动作->换句话说,当它是addOnSuccessListener

你知道我该怎么做吗?

我习惯于快速编码,就像这样:

func addUser(id: String, completion: @escaping (User) -> Void) {
      // Code and then
      completion(user)
   }

您应该为自己的 MyFirebaseListener创建自定义监听器 ,并通过实现此接口来更新活动中的内容

public interface MyFirebaseListener {
    void onSuccess(DocumentReference documentReference)
    void onFailure(Exception e)
}

现在,将Activity作为参数传递给MyFirebaseListener以使用addNewUser()方法,如下所示

public class UserApi{

    public void addNewUser(String firstname, 
                String lastname, 
                String email, 
                Integer gender, 
                String uid, 
                String profileImageUrl,
                MyFirebaseListener myFirebaseListener){

        Map<String, Object> data = new HashMap<>();
        data.put("firstname", firstname);
        data.put("lastname", lastname);
        data.put("email", email);
        data.put("gender", gender);
        data.put("boxId", "independent");
        data.put("notificationsEnabled", true);
        data.put("profileImageUrl", profileImageUrl);

        mFirebaseFirestore.collection("usersP").add(data)
                .addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
                    @Override
                    public void onSuccess(DocumentReference documentReference) {
                        myFirebaseListener.onSuccess(documentReference)
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        myFirebaseListener.onFailure(e)
                    }
                });

    }
}

在您的Activity中实现MyFirebaseListener接口,因此您需要重写以下方法,并在这些实现的方法中执行UI修改 ,如下所示

public class MyActivity extends AppCompatActivity implements MyFirebaseListener {

    void someMethod(){
        addNewUser(firstname, 
                lastname, 
                email, 
                gender,
                uid,
                profileImageUrl,
                this) // <- This will be reference to Activity with Type of MyFirebaseListener
    }

    void onSuccess(DocumentReference documentReference){
        mProgressBar.setVisibility(View.GONE);
        mIRegisterActivity.inflateFragment("Register Box", mHashMap);
        Log.d(TAG, "DocumentSnapshot written with ID: " + documentReference.getId());
    }
    void onFailure(Exception e){
        Log.d(TAG, "Error adding document", e);
    }
}

这是您可以使用自定义界面分离 UI逻辑和服务逻辑的方法

请参阅此链接以获取自定义侦听器: https : //guides.codepath.com/android/Creating-Custom-Listeners

如果要始终保持侦听器调用,对于Firebase侦听器,请对侦听器使用应用程序类

如果您想要全局方法(需要Firebase响应的方法),则将该函数放在Application类中,或者使用BroadcastReceiverListenerEventBus

如果您有任何疑问,请在这里评论。

只需添加一个界面...

public interface IFirebaseTask {
    void OnSuccess(DocumentReference reference);
    void OnFailure(Exception e);
}

然后实现该接口,可能需要在其中侦听:

public SomeActivity extends FragmentActivity implements IFirebaseTask {

}

也可以将侦听器传递给构造函数:

public SomeFirebaseTask(Context context, IFirebaseTask listener){
    this.setContext(context);
    this.listener = listener;
}

...以便从其他地方通知上面定义的侦听器。

或者,可以让任何类实现接口方法:

... implements OnSuccessListener<DocumentReference>, OnFailureListener

然后像这样绑定监听器:

mFirebaseFirestore
  .collection("usersP")
  .add(data)
  .addOnSuccessListener(SomeActivity.this)
  .addOnFailureListener(SomeActivity.this);

Firebase文档(以防有人不愿阅读)也有此答案...

请参阅“ 分离回调”部分。

首先添加listenerInterface

public interface FirebaseResponse {
     void onSuccess();
     void onFailure();
}

创建单独的类,如下所示

public class ResponseHandler implements
    OnSuccessListener<DocumentReference>() , OnFailureListener() {

            private FirebaseListener listener;

            public ResponseHandler(FirebaseListener listener){
                 this.listener = listener;
            }     


             @Override
             public void onSuccess(DocumentReference documentReference) {
              //Todo handle onSuccess
                 listener.onSuccess();
             }

             @Override
             public void onFailure(@NonNull Exception e) {
                //Todo handle onFailure
                 listener.onFailure();
             }
    }

然后将此类添加为实现FirebaseListener的类中的响应处理程序

ResponseHandler responseHandler = new ResponseHandler(this);

mFirestore.collection("usersP").add(data)
                .addOnSuccessListener(responseHandler).
                .addOnFailureListener(responseHandler)

您可以使用两种不同的方法...首先:您可以像在RecyclerView点击回调的情况下一样,创建一个回调接口...

第二:如果您必须对rxJava2,arch life或Agera有一点了解,那么您可以使用livedata观察器。

因此,让我们考虑第一个方法

考虑到你的班级是

class otherClass{
callbackInterface mCallBackInterface;

public(callbackInterface mCallBackInterface){
this.mCallBackInterface=mCallBackInterface;
}

interface callbackInterface{
void onSucuss(DocumentReference documentReference);
}


public void addNewUser(String firstname, String lastname, String email, Integer gender, String uid, String profileImageUrl){

        Map<String, Object> data = new HashMap<>();
        data.put("firstname", firstname);
        data.put("lastname", lastname);
        data.put("email", email);
        data.put("gender", gender);
        data.put("boxId", "independent");
        data.put("notificationsEnabled", true);
        data.put("profileImageUrl", profileImageUrl);

        mFirebaseFirestore.collection("usersP").add(data)
                .addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
                    @Override
                    public void onSuccess(DocumentReference documentReference) {

mCallBackInterface.onSucuss(decumentReference);


                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Log.d(TAG, "Error adding document", e);
                    }
                });

    }

}

///The Class which will be calling it will be something like this

class CallingClass implements CallBackInterface{

@Override
void CallBackINterface(DocumentReference documentReference){

//Your code goes here
}

}

这将做工作广播接收器也可以使用,但以上解决方案最适合初学者...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM