Search code examples
androidjsondictionaryspinner

How to populate Json String into Android spinner


My Json response is not an array. It is a single Json object (That has dynamic Keys and values pairs as below):

{
    "key1": "value1",
    "key2": "value2",
    "key3": "value3",
    "key4": "value4",
    "key5": "value5",
    "key6": "value6",
    "key7": "value7",
    "key8": "value8",
}

How to populate values into Android spinner or How to create a Map from this Json response?


Solution

  • Ok I found the solution. For the response type I did not use JsonObject. I used HashMap<String, String>

         @GET("api")
     fun getListItems(
             @Header(NetworkUtils.CONTENT_TYPE) contentType: String = NetworkUtils.CONTENT_TYPE_PARAMS,
             @Header(NetworkUtils.AUTHORIZATION) bearerToken: String,
             @Query("language") language: String?
    ): Observable<Response<HashMap<String, String>>>
    

    Then just use the HashMap on the Spinner

    override fun populatesCaseTypesSpinner(response: HashMap<String, String>) {
         val adapter = ArrayAdapter(context!!, android.R.layout.simple_spinner_item, ArrayList(response.keys))
    
         adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
    
         spinnerCaseTypes.adapter = adapter
    
         spinnerCaseTypes.setOnTouchListener(View.OnTouchListener { _, _ ->
             hideKeyboard()
             false
         })
    

    }