Kotlin (Volley)에서 getParam을 재정의 할 수 없습니다.

Nov 25 2020

getParam아래와 같이 재정의 할 수 없습니다 . 누군가 getParamKotlin 에서 재정의하는 방법을 설명 할 수 있기를 바랍니다 .

build.gradle

implementation 'com.android.volley:volley:1.1.1'

fun testpost(button: Button)
{
    val url = "http://192.168.178.23/insertcode.php"
    val queue = Volley.newRequestQueue(this)


    val stringRequest = StringRequest(Request.Method.POST, url,
            { response ->
                button.text = "Response is: ${response}"
            },
            { button.text = "That didn't work!" })
    {
        override fun getParam(){

        }
    }
    queue.add(stringRequest)
}

답변

1 DavidKroukamp Nov 25 2020 at 21:18

당신은 할 수 없습니다, 그것은 StringRequest그 문제에 대한 어떤 다른 내장 요청에 노출되지 않습니다 . 이것이 실제로 필요한 작업이라면 안타깝게도 사용자 지정 요청을 만들어야합니다 .

다음은 생성자 ( Kotlin ) 에서 StringRequest지정할 수 있는 Custom의 예입니다 .params

import androidx.annotation.GuardedBy
import com.android.volley.NetworkResponse
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.HttpHeaderParser
import java.io.UnsupportedEncodingException
import java.nio.charset.Charset

class CustomStringRequest(
    method: Int,
    url: String,
    listener: Response.Listener<String>,
    errorListener: Response.ErrorListener?,
    private val params: MutableMap<String, String>
) : Request<String>(method, url, errorListener) {

    private val lock = Any()

    @GuardedBy("lock")
    private var listener: Response.Listener<String>? = listener

    override fun getParams(): MutableMap<String, String> {
        return params
    }

    override fun cancel() {
        super.cancel()
        synchronized(lock) { listener = null }
    }

    override fun deliverResponse(response: String) {
        var listener: Response.Listener<String>?
        synchronized(lock) { listener = this.listener }
        if (listener != null) {
            listener!!.onResponse(response)
        }
    }

    override fun parseNetworkResponse(response: NetworkResponse): Response<String> {
        val parsed: String = try {
            String(response.data, Charset.forName(HttpHeaderParser.parseCharset(response?.headers)))
        } catch (e: UnsupportedEncodingException) {
            // Since minSdkVersion = 8, we can't call
            // new String(response.data, Charset.defaultCharset())
            // So suppress the warning instead.
            String(response.data)
        }

        return Response.success(
            parsed,
            HttpHeaderParser.parseCacheHeaders(response)
        )
    }
}

그런 다음 다음과 같이 사용합니다.

// Instantiate the RequestQueue.
val queue = Volley.newRequestQueue(activity)
val url = "YOUR_URL"

// Request a string response from the provided URL.
val stringRequest = CustomStringRequest(
    Request.Method.POST, url,
    Response.Listener { response ->
        // TODO do something with response
    },
    Response.ErrorListener {
        // TODO handle errors
    },
    hashMapOf("name" to "value") // TODO add your params here
)

// Add the request to the RequestQueue.
queue.add(stringRequest)
1 Danixo Nov 26 2020 at 00:06

StringRequest 앞에 객체를 입력하면 이제 getParams 메소드를 사용할 수 있습니다.

코드는 다음과 같습니다.

fun testpost(button: Button)
    {
        val url = "http://192.168.178.23/insertcode.php"
        val queue = Volley.newRequestQueue(this)


        val stringRequest = object :StringRequest(Request.Method.POST, url,
            { response ->
                button.text = "Response is: ${response}"
            },
            { button.text = "That didn't work!" })
        {
            //Press Ctr + O to find getParams
            override fun getParams(): MutableMap<String, String> {
                val hashMap = HashMap<String, String>()
                hashMap.put("name", "peter")
                return hashMap
            }
        }
        queue.add(stringRequest)
    }