Reputation: 11
In the below code I am receiving a ByteArray object as a response. Now I want to download the file and preview the file.
For that I had created custom request class, but it is giving two errors. The code below contains listener
and Response<ByteArray>
as errors:
ByteArrayRequest.kt:
class ByteArrayRequest(
context: Context,
fileName: String,
method: Int,
url: String,
jsonRequest: JSONObject?,
listener: Response.Listener<Unit>, // or custom listener with downloaded file
errorListener: Response.ErrorListener,
) : JsonObjectRequest(method, url, jsonRequest, listener, errorListener) {
private val headers: MutableMap<String, String> = HashMap()
private val context = context
private val fileName = fileName
fun addHeader(key: String, value: String) {
headers[key] = value
}
override fun parseNetworkResponse(response: NetworkResponse): Response<ByteArray> {
val data = response.data
if (checkWriteExternalStoragePermission()) {
val file = File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), fileName)
try {
FileOutputStream(file).use { output ->
output.write(data)
}
} catch (e: IOException) {
// Handle IO exception
return Response.error(VolleyError(e))
}
Response.success(Unit, HttpHeaderParser.parseCacheHeaders(response))
} else {
// Handle permission denied case
return Response.error(VolleyError(Exception("Storage permission denied")))
}
}
private fun checkWriteExternalStoragePermission(): Boolean {
return ContextCompat.checkSelfPermission(
context,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE
) == PackageManager.PERMISSION_GRANTED
}
override fun getHeaders(): MutableMap<String, String> {
return headers
}
}
Activity:
fun submitdata(url: String) {
//new HttpsTrustManager().allowAllSSL();progressBar.setVisibility(View.VISIBLE);
val js = JSONObject()
try {
js.put("year", financialyear!!.selectedItem.toString().toInt())
js.put("month", month!!.selectedItem.toString().toInt())
js.put("emp_number", emp_num)
Log.d("volley","js:${js}")
} catch (e: JSONException) {
e.printStackTrace()
}
val byteArrayRequest = ByteArrayRequest(
context = applicationContext,
fileName = "report.pdf",
method = Request.Method.POST,
url = url,
jsonRequest = js,
listener = {
// Handle the byte array response here
Toast.makeText(applicationContext, "File downloaded to: ", Toast.LENGTH_SHORT).show()
},
errorListener = { error ->
Log.d("volley","Error:${error.message}")
},
)
byteArrayRequest.retryPolicy = DefaultRetryPolicy(
100000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT
)
byteArrayRequest.addHeader("Authorization", "Bearer " + SharedPrefrence.getApitoken(applicationContext))
byteArrayRequest.addHeader("x-api-key", SharedPrefrence.getApikey(applicationContext)!!)
// Add the request to a request queue
val requestQueue = Volley.newRequestQueue(applicationContext)
requestQueue.add(byteArrayRequest)
}
Upvotes: 1
Views: 26