2017-11-21 8 views
1

서버에 php 파일이 있는데 정보를 가져와야하지만 쿼리에 매개 변수를 전달하는 방법을 모르겠습니다.kotlin에서 volley 라이브러리를 사용하여 정보를 가져 오는 방법

예를 들어, 다음 쿼리가있는 경우 SELECT * FROM accounttable where idaccount = 1,이 매개 변수를 매개 변수로 전달하려면 어떻게해야합니까?

val stringRequest = StringRequest(Request.Method.POST, URL, Response.Listener<String>{ s -> 
     try { 

       val array = JSONArray(s) 

       for (i in 0..array.length() - 1) { 
        val objectAccount = array.getJSONObject(i) 
        val account = Account(
          objectAccount.getString("accountplace"), 
          objectAccount.getString("useraccount"), 
          objectAccount.getString("accountpass")) 

        listAccounts.add(account) 

       } 


     }catch (e: JSONException){ 
      e.printStackTrace() 
     } 
    }, Response.ErrorListener { error: VolleyError? -> Log.e("error", "error") }) 

    val requesQueue = Volley.newRequestQueue(this) 
    requesQueue.add<String>(stringRequest) 

답변

3

당신은 당신의 RequestgetParams() 메소드를 오버라이드 (override) 할 필요가있다. 이를 수행하려면 StringRequest을 서브 클래스 화하거나 object expression을 작성하십시오 (Java에서 anonymous inner class과 유사). 아래 그림과 같이.

val stringRequest = object : StringRequest(Request.Method.POST, URL, Response.Listener { s -> 
    // Your success code here 
}, Response.ErrorListener { e -> 
    // Your error code here 
}) { 
    override fun getParams(): Map<String, String> = mapOf("idaccount" to "1") 
} 
+1

고맙습니다! 그것은 효과가있다! 왜 객체를 써야하는지 설명해 주시겠습니까? StringRequest? 왜냐하면 이것 없이는 getParams 메쏘드를 오버라이드 할 수 없었기 때문입니다. – zasaz

+0

@zasaz 그것은 객체 표현을위한 문법입니다 (위에서 언급했듯이, 자바의 익명의 클래스 선언을 대체합니다). 그것은 Kotlin에서 익명 클래스의 객체를 만드는 유일한 방법입니다. * 왜 * 언어 디자이너가 특정 구문을 사용했는지에 대한 단서는 없습니다. – Bryan

+0

@Bryan 어떻게'stringRequest'를 queque에 추가합니까? 'queque.add (stringRequest)'오류 발생'클래스 본체 기대' – AlexAndro