Файл не сохраняется в загрузках на андроиде

Привет, файл ниже нигде не сохраняется, и я пробовал во всех местах, но файл не существует. Ниже приведен code, получающий ответ Ответ:[B@1331d46 и отправляющий массив байтов, отправляющий его в файл и сохраняющий его локально

Может ли кто-нибудь помочь мне, где он был сохранен и в чем проблема с codeом ниже

файл для загрузки на телефон

class ByteArrayRequest (
    method: Int,
    url: String,
    context: Context,
    jsonRequest: JSONObject?,
    listener: Response.Listener<ByteArray>,
    errorListener: Response.ErrorListener
) : JsonRequest<ByteArray>(method, url, jsonRequest?.toString(), listener, errorListener)
{
    private val headers: MutableMap<String, String> = HashMap()

    private val context = context

    fun addHeader(key: String, value: String) {
        headers[key] = value
    }


    override fun parseNetworkResponse(response: NetworkResponse): Response<ByteArray>? {

        return try {
            val data = response.data
            val file = createPdfFile(context) // Create the file before writing
            val fileOutputStream = FileOutputStream(file)
            fileOutputStream.write(response.data)
            fileOutputStream.close()

            Response.success(
                response.data,
                HttpHeaderParser.parseCacheHeaders(response)
            )
        } catch (e: UnsupportedEncodingException) {
            Response.error(ParseError(e))

        }
    }

    override fun getHeaders(): MutableMap<String, String> {
        return headers
    }

    private fun createPdfFile(context: Context): File {
        val fileDir = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
        val pdfFile = File(fileDir, "generated.pdf") // Replace with desired name
        if (!pdfFile.exists()) {
            pdfFile.createNewFile() // Create the file if it doesn't exist
        }
        return pdfFile
    }

}
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(
            Request.Method.POST,
            url,
            applicationContext,
            js,
            { response ->
                // Handle the byte array response here
                Log.d("volley","Response:${response}")
                convertByteArrayToPdf(applicationContext,response)

            },
            { 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)

    }
    private fun convertByteArrayToPdf(context: Context, byteArray: ByteArray) {
        val fileDir = applicationContext.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
        val pdfFile = File(fileDir, "generated.pdf") // Replace with desired name

        try {
            val fos = FileOutputStream(pdfFile)
            fos.write(byteArray)
            fos.close()
        } catch (e: Exception) {
            // Handle exception
        }
    }
Евгения
Вопрос задан9 января 2024 г.

1 Ответ

2
Фёкла
Ответ получен19 сентября 2024 г.

Ваш ответ

Загрузить файл.