gpt4 book ai didi

java - 在 Android 和 Java 上复制 Swift 完成处理程序

转载 作者:行者123 更新时间:2023-11-29 07:25:26 27 4
gpt4 key购买 nike

多年后,我尝试使用 Firebase Firestore 开发一款 Android 应用。我基本上是在尝试复制这个 Swift 函数:

func getCategories(onCompletion completionBlock: @escaping (_ categories: [Category]?, _ error: Error?) -> Void) {

firestore.collection("cats").getDocuments { (snap, error) in
guard let snap = snap else {
completionBlock(nil, error ?? anUnknownError)
return
}

var categories: [Category] = []
for document in snap.documents {
let cat = Category.init(data: document.data())
categories.append(cat)
}
completionBlock(categories, nil)
}
}

但是我不知道swift的 block 相当于什么,甚至不知道它是否存在。

我检查了 Firebase 源代码。 Query.get()返回 Task<QuerySnapshot>所以我试图返回 Task<List<Category>>没有运气。

有什么帮助吗?谢谢。

编辑:添加 Android 代码以阐明我正在尝试做的事情。

public class FirestoreService {

private static volatile FirestoreService singleton = new FirestoreService();

public static FirestoreService getInstance() {
return singleton;
}

private FirebaseFirestore firestore() {
// default firestore instance
FirebaseFirestore db = FirebaseFirestore.getInstance();

// default firestore settings
FirebaseFirestoreSettings settings = db.getFirestoreSettings();

// firestore settings builder
FirebaseFirestoreSettings.Builder builder = new FirebaseFirestoreSettings.Builder(settings);

// enable timstamps
builder.setTimestampsInSnapshotsEnabled(true);

// set new settings to db instance
db.setFirestoreSettings(builder.build());


// return db with new settings.
return db;
}



public void getProductCategories(Handler? handler) {

Task<QuerySnapshot> task = firestore().collection("coll").get();
task.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
try {
if (task.isSuccessful()) {
List<Category> cats = new ArrayList<>();
for (QueryDocumentSnapshot doc : task.getResult()) {
String id = doc.getId();
Map<String, Object> data = doc.getData();
Category cat = new Category(id, data);
cats.add(cat);
}
// now I need completion handler
} else {
Log.w("ERROR", "Error getting categories", task.getException());
}
} catch (Exception e) {
Log.e("ERROR", e.getMessage());
}
}
});
}

}



public class MainActivity extends AppCompatActivity {

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

FirestoreService.getInstance().getCategories().addCompletionListener(
// handle List<Category> and respresent in UI
);
}
}

最佳答案

非常感谢四位的帮助和领导@Daniel-b。

我现在已经解决了我的问题。

首先,我创建了一个用于处理结果的接口(interface);正如你所建议的。

public interface ResultHandler<T> {
void onSuccess(T data);
void onFailure(Exception e);
}

然后在服务类中,我将 ResultHandler 添加到函数的输入参数中:

public void getUserInfo(String id, ResultHandler<UserInfo> handler) {
firestore().collection("userInfo").document(id).get().addOnCompleteListener(snap -> {
if (snap.isSuccessful()) {
try {
// failable constructor. use try-catch
UserInfo info = new UserInfo(snap.getResult().getId(), snap.getResult().getData());
handler.onSuccess(info);
} catch (Exception e) {
handler.onFailure(e);
}
} else {
handler.onFailure(snap.getException())
}
});
}

并在Activity中调用服务

FirestoreService.getInstance().getUserInfo("ZsrAdsG5HVYLTZDBeZtkGDlIBW42", new ResultHandler<UserInfo>() {
@Override
public void onSuccess(UserInfo data) {
Log.i("UserInfo", data.id);
}

@Override
public void onFailure(Exception e) {
// getting data failed for some reason
}
});

关于java - 在 Android 和 Java 上复制 Swift 完成处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53979480/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com