gpt4 book ai didi

java - 将 kotlin 转换为 java 以传递给 Firestore

转载 作者:行者123 更新时间:2023-12-02 01:50:58 24 4
gpt4 key购买 nike

我想在java文件中的kotlin文件上使用这个方法,不幸的是我不知道如何在java中做到这一点。有人可以帮我吗?

Kotlin 代码更改为 Java:

val progressDialog = indeterminateProgressDialog("Setting up your module")
FirestoreUtil.getImportModules(ID, applicationContext) {
val intent = Intent(this@AddModActivity, EditImportUserActivity::class.java)
intent.putExtra("moduleID", ID)
intent.putExtra("moduleCode", code)
intent.putExtra("moduleName", name)
startActivity(intent)
progressDialog.dismiss()
}

它在firstore util中调用此方法(不需要更改)

fun getImportModules(String: String = "", context : Context, onComplete: () -> Unit) {
firestoreInstance.collection("assessment").whereEqualTo("module", String).get()
.addOnSuccessListener { documentSnapshot ->
lateinit var realm: Realm
Realm.init(context)
val defaultConfig = RealmConfiguration.Builder()
.schemaVersion(0)
.build()
realm = Realm.getInstance(defaultConfig)
val results = realm.where(Assessment::class.java).findAll()
realm.executeTransaction {
results.deleteAllFromRealm()
}
if (documentSnapshot.isEmpty) {
onComplete()
}
else
{
documentSnapshot!!.documents.forEach {
val s = Assessment(Double.parseDouble(it.get("achieved")!!.toString()),
it.get("date")!!.toString(), it.get("desc")!!.toString(), it.get("module")!!.toString(),
it.get("time")!!.toString(), Double.parseDouble(it.get("total")!!.toString()), it.get("type")!!.toString(),
it.get("weight")!!.toString())
//SAVE
val helper = RealmHelper(realm)
helper.save(s)
}
onComplete()
}
}
}

我知道如何制作进度对话框和 Intent ,我不知道如何将 Intent 传递给方法onComplete()

提前谢谢

最佳答案

() -> Unit 转换为 Kotlin 中 Function 接口(interface)的实例。

这意味着您应该能够创建它的一个实例:

FirestoreUtil.getImportModules(ID, getApplicationContext(), new Function<Unit>() {
@Override
public Unit invoke() {
Intent intent = new Intent(AddModActivity.this, EditImportUserActivity.class)
intent.putExtra("moduleID", ID)
intent.putExtra("moduleCode", code)
intent.putExtra("moduleName", name)
startActivity(intent)
progressDialog.dismiss()
return Unit.INSTANCE; //notice this line; Kotlin treats the Unit class as void, but Java treats it as an actual class
});

如果您使用 Java 8(面向 API 24 或更高版本并启用它),则可以使用 lambda,这会使其更短:

FirestoreUtil.getImportModules(ID, getApplicationContext(), () -> {
Intent intent = new Intent(AddModActivity.this, EditImportUserActivity.class)
intent.putExtra("moduleID", ID)
intent.putExtra("moduleCode", code)
intent.putExtra("moduleName", name)
startActivity(intent)
progressDialog.dismiss()
return Unit.INSTANCE;
});

关于java - 将 kotlin 转换为 java 以传递给 Firestore,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52995850/

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