【问题标题】:Making a Reqeust class in kotlin with Volley使用 Volley 在 kotlin 中创建请求类
【发布时间】:2019-12-19 01:44:59
【问题描述】:

我正在尝试用 kotlin 创建一个通用的 Request 类,我可以用它来用 Volley 发出 Request。

我遇到的问题是我无法返回请求的响应。

我正在尝试获取请求的响应,以便处理数据。

我似乎找不到一个很好的资源来描述如何制作一个 Helper 类来发出请求

请求类

import android.content.Context
import android.util.Log
import com.android.volley.RequestQueue
import com.android.volley.Response
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley

class Request(var context: Context, var url: String) {

    var response : String? = null

    fun makePOSTRequest() {

        val requestQueue: RequestQueue? = Volley.newRequestQueue(context)

        val stringRequest = object : StringRequest(
            Method.POST, url,
            Response.Listener { response ->

            }, Response.ErrorListener { error ->
                Log.i("Error", "[" + error + "]")
            }) {

            override fun getParams(): Map<String, String> {
                val params = HashMap<String, String>()
                return params
            }

        }

        requestQueue?.add(stringRequest)

    }

    fun makeGETRequest() {

        val requestQueue: RequestQueue? = Volley.newRequestQueue(context)

        val stringRequest = object : StringRequest(
            Method.GET, url,
            Response.Listener { response ->

                println(response) // Response: {"message":"ok","locaties"[{"id":"739","name":"Company","code":"","klant":"Client"}]}


               this.response = response // Here I'm trying to fill the response var



            }, Response.ErrorListener { error ->
                Log.i("Error", "[" + error + "]")
            }) {
        }

        requestQueue?.add(stringRequest)

    }


}

实施

var request = context?.let { Request(it, BuildConfig.API_URL + "getLocatiesLijst.php?name=" + bdl?.getString("name")) }

        request?.makeGETRequest()

        var response = request?.response

        println(response) // This give Null back

【问题讨论】:

标签: android kotlin


【解决方案1】:

我一直忙于用协程实现一个请求助手类。我想我已经找到了解决我自己问题的方法。我正在使用协程使请求异步。

Source of solution

请求.kt

import android.content.Context
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import kotlin.coroutines.*;

class Request(var context: Context, var url: String) {

    suspend fun makeGetRequest() = suspendCoroutine<String> { cont ->
        val queue = Volley.newRequestQueue(context)

        val stringRequest = StringRequest(
            Request.Method.GET, url,
            Response.Listener<String> { response ->
                cont.resume("Response is: ${response}")
            },
            Response.ErrorListener { cont.resume("Something went wrong!") })

        queue.add(stringRequest)
    }

}

实施

class LocationFragment : Fragment(), CoroutineScope {

     protected lateinit var job: Job
     override val coroutineContext: CoroutineContext
                get() = job + Dispatchers.Main

     override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {

        var rootView =  inflater.inflate(R.layout.location_list, container, false)

        //TODO doe verzoek voor lijst van locaties

        val bdl = arguments

        var request = context?.let { Request(it, BuildConfig.API_URL + "getLocatiesLijst.php?name=" + bdl?.getString("name")) }

         job = Job()

         launch {
             val data = request?.makeGetRequest()
             println(data)
         }
    }

结果

I/System.out:响应为:{"message":"ok","locaties":[{"id":"739","name":"Company","lce_code":"code" ,"klant":"客户"}]}

【讨论】:

  • 很好,但永远不要在 UI 类中做这样的事情。至少使用 ViewModels
【解决方案2】:

我猜问题是请求是异步的,但是当你运行它时, println("") 将立即被调用。你应该等待结果。 您可以向监听器添加一些回调或尝试使用协程。

【讨论】:

  • 感谢您的建议,我对协程进行了一些研究,并找到了解决方案。在下面检查我的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-01
  • 1970-01-01
  • 2021-07-08
相关资源
最近更新 更多