我想通过 Java 和 Kotlin 发出简单的 Volley POST 请求。我在我的应用程序中使用两种语言,因此我尽力使用两种语言。 我过来了this使用 Kotlin 中的以下 VolleyClass 进行教程:
类 WolfRequest(val url: 字符串, 验证结果:(JSONObject) -> 单位, val 错误:(字符串)-> 单位){
fun POST(vararg params: Pair<String, Any>) {
// HashMap to pass arguments to Volley
val hashMap = HashMap<String, String>()
params.forEach {
// Convert all Any type to String and add to HashMap
hashMap[it.first] = it.second.toString()
}
// Make the Http Request
makeRequest(Request.Method.POST, hashMap)
}
private fun makeRequest(method: Int, params: HashMap<String, String>) {
// Creating a StringRequest
val req = object : StringRequest(method, url, { res ->
// Creating JSON object from the response string
// and passing it to result: (JSONObject) -> Unit function
result(JSONObject(res.toString().trim()))
}, { volleyError ->
// Getting error message and passing it
// to val error: (String) -> Unit function
error(volleyError.message!!)
}) {
// Overriding getParams() to pass our parameters
override fun getParams(): MutableMap<String, String> {
return params
}
}
// Adding request to the queue
volley.add(req)
}
// For using Volley RequestQueue as a singleton
// call WolfRequest.init(applicationContext) in
// app's Application class
companion object {
var context: Context? = null
val volley: RequestQueue by lazy {
Volley.newRequestQueue(context
?: throw NullPointerException(" Initialize WolfRequest in application class"))
}
fun init(context: Context) {
this.context = context
}
}
}
我正在尝试从 Java.Class 访问此代码以进行 POST Reuqest:
WolfRequest.Companion.init(getApplicationContext());
HashMap <String, String> params = new HashMap <> ();
params.put("id", "123");
new WolfRequest(config.PING_EVENTS,*new WolfRequest()*
{
public void response(JSONObject response) {
Log.e("Ping","PING");
}
public void error(String error) {
Log.e("Ping",error);
}
}).POST(params);
这里给了我一个错误(new WolfRequest()):无法从最终的“...wolfrequest.kt”继承
我真的没有收到错误,这里有什么问题?
谢谢
最佳答案
kotlin 中的类默认是 Final 的。要创建非最终类,您需要将其声明为open
。所以开放类WolfRequest
使用 java 中的 new WolfRequest() {}
,您可以创建一个扩展 WolfRequest
的匿名类,因此您会从最终类继承得到该错误。
要实际调用 WolfRequest 的构造函数,您需要传递三个参数。像这样的东西:
new WolfRequest("", (s) -> Unit.INSTANCE, (s) -> Unit.INSTANCE){
....
}
关于java - Volley : Kotlin Class call from JavaCode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56997004/