jyothi
jyothi

Reputation: 1

NetworkUtility.shouldRetryException: Unexpected response code 400 in android kotlin volley

I am receiving byte array and converting into file and downloading the file and view it in pdf file .

for parsing json I am using volley libray to parse the json request. I had two spinner if user select year and month we are receiving byte array as a response.

But I am getting NetworkUtility.shouldRetryException: Unexpected response code 400 .
in this image contains request and respnse.

Below one the code:

class PayslipActivity : Activity() {
    var financialyear: Spinner? = null
    var month: Spinner? = null
    var emp_num: String? = null
    var msg: String? = null
    var statusCode = 0
    var preview: Button? = null
    var download: Button? = null
    var progressBar: ProgressBar? = null
    var stringArrayList: ArrayList<String?> = ArrayList()
    var monthArrayList: ArrayList<String?> = ArrayList()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_payslip)


        val toolbartitle: TextView = findViewById<TextView>(R.id.txt_toolbar_title)

        toolbartitle.setText("My PaySlip")
        stringArrayList.add("2023")
        stringArrayList.add("2024")
        progressBar = findViewById(R.id.progressBar)
        financialyear = findViewById(R.id.financial_year)
        month = findViewById(R.id.month)
        monthArrayList.add("5")
        monthArrayList.add("6")
        preview = findViewById(R.id.btn_preview)
        val adapter1 = ArrayAdapter(
            applicationContext,
            android.R.layout.simple_dropdown_item_1line,
            stringArrayList
        )
        adapter1.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line)
        financialyear!!.setAdapter(adapter1)

        val adapter2 = ArrayAdapter(
            applicationContext,
            android.R.layout.simple_dropdown_item_1line,
            monthArrayList
        )
        adapter2.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line)
        month!!.setAdapter(adapter2)

        financialyear?.setOnItemSelectedListener(object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>,
                view: View,
                position: Int,
                id: Long
            ) {
                (parent.getChildAt(0) as TextView).setTypeface(null, Typeface.BOLD)

            }

            override fun onNothingSelected(parent: AdapterView<*>?) {}
        })

        month?.setOnItemSelectedListener(object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>,
                view: View,
                position: Int,
                id: Long
            ) {
                (parent.getChildAt(0) as TextView).setTypeface(null, Typeface.BOLD)

            }

            override fun onNothingSelected(parent: AdapterView<*>?) {}
        })

        preview!!.setOnClickListener(View.OnClickListener {

            submitdata(SharedPrefrence.getApiurl(applicationContext)
                    .toString() + "/api/v1/payroll/payslip")

        })
    }

    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("exp_number", emp_num)
        } catch (e: JSONException) {
            e.printStackTrace()
        }
        val stringRequest: JsonObjectRequest = object : JsonObjectRequest(
            Method.POST, url, js,
            Response.Listener { response ->
                val pdfUrl = response.getString("pdfUrl") // Assuming the response contains a PDF URL
                fetchPdf(applicationContext, pdfUrl)
            },
            Response.ErrorListener {error ->
                Log.e("Volley", "Error: $error")
                if (error is VolleyError && error.networkResponse != null) {
                    val statusCode = error.networkResponse.statusCode
                    if (statusCode == 400) {
                        // Handle 400 error specifically
                        Log.e("Volley", "Bad Request: ${error.message}")
                        // Provide user-friendly error message
                    }
                }
            }) {

            @Throws(AuthFailureError::class)
            override fun getHeaders(): Map<String, String> {
                val headers = HashMap<String, String>()
                headers["Authorization"] = "Bearer " + SharedPrefrence.getApitoken(applicationContext)
                headers["x-api-key"] = SharedPrefrence.getApikey(applicationContext)!!
                headers["Content-Type"] = "application/json"
                return headers
            }
        }
        stringRequest.retryPolicy = DefaultRetryPolicy(
            100000,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT
        )
        val requestQueue = Volley.newRequestQueue(this)
        requestQueue.add(stringRequest)
    }


    @SuppressLint("ServiceCast")
    private fun fetchPdf(context: Context, pdfUrl: String) {
        val downloadManager = applicationContext.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager

        val request = DownloadManager.Request(Uri.parse(pdfUrl)).setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI or DownloadManager.Request.NETWORK_MOBILE)
            .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
            .setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
        "payslip.pdf")

        val downloadId = downloadManager.enqueue(request)

        // Register a broadcast receiver to listen for download completion
        // ...

        // Once download is complete (e.g., in a broadcast receiver):
        val intent = Intent(Intent.ACTION_VIEW)
        intent.setDataAndType(Uri.fromFile(File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
            "payslip.pdf")), "application/pdf")
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        context.startActivity(intent)
    }

    }

Expecting PDF view and download as response

Upvotes: 0

Views: 22

Answers (0)

Related Questions