我正在尝试通过自己的 JSON 搜索后端来实现。
在 ML Kit 中,搜索引擎使用 Volley 来处理请求。
一旦检测到条形码,detectedBarcode
就会运行:
LiveBarcodeScanningActivity.kt:
workflowModel?.detectedBarcode?.observe(this, Observer { barcode ->
if (barcode != null) {
val barcodeFieldList = ArrayList<BarcodeField>()
barcodeFieldList.add(BarcodeField("Raw Value", barcode.rawValue ?: ""))
searchEngine!!.search(barcode) { productList, product ->
workflowModel?.onSearchCompletedV2(product, productList)
}
}
})
搜索引擎.kit
class SearchEngine(context: Context) {
private val searchRequestQueue: RequestQueue = Volley.newRequestQueue(context)
private val requestCreationExecutor: ExecutorService = Executors.newSingleThreadExecutor()
fun search(
barcode: Barcode,
listener: (productList: List<Product>, product: Product) -> Unit
) {
Tasks.call<JsonObjectRequest>(requestCreationExecutor, Callable { createRequest(barcode) })
.addOnSuccessListener { productRequest ->
//Planning to map the JSON request data to the product object and add to the productList
val product = Gson().fromJson(productRequest, Product::class.java) // None of the following functions can be called with the arguments supplied.
listener.invoke(barcode, product)
}
.addOnFailureListener { e ->
Log.e(TAG, "Failed to create product search request!", e)
}
}
fun shutdown() {
searchRequestQueue.cancelAll(TAG)
requestCreationExecutor.shutdown()
}
companion object {
private const val TAG = "SearchEngine"
var url = "REQUEST URL"
@Throws(Exception::class)
private fun createRequest(barcode: Barcode): JsonObjectRequest {
// Hooks up with your own product search backend here.
return JsonObjectRequest(Request.Method.GET, url, null,
{ response ->
print("JSON request was a success$response")
},
{ error ->
throw Exception("Failed to get product!$error")
}
)
}
}
}
我得到“不能使用提供的参数调用以下函数。” 当我试图从 JsonObjectRequest 转换为 Product 对象时。
@Serializable
data class Product internal constructor(val imageUrl: String, val title: String, val subtitle: String)
这是我试图将 JSON 数据从我的请求映射到的 Product 对象。