如何使用Kotlin,翻新和RXjava来填充列表视图
我与服务的整合已经准备就绪,我可以在请求日志中看到我的数组,但是我无法填充列表视图。
我真的已经尝试了我所知道的一切,我对kotlin是新的,语言让我有点困惑。 有人可以找出错误的地方,我做错了。
JSON /请求:
{"0":{"id":1,"nome":"teste"},"1":{"id":2,"nome":"teste 2"}}
apiClient.kt
val service : ApiInterface val URL = "json" init { val logging = HttpLoggingInterceptor() logging.level = HttpLoggingInterceptor.Level.BODY val httpClient = OkHttpClient.Builder() httpClient.addInterceptor(logging) val gson = GsonBuilder().setLenient().create() val retrofit = Retrofit.Builder() .baseUrl(URL) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create(gson)) .client(httpClient.build()) .build() service = retrofit.create<ApiInterface>(ApiInterface::class.java) }
ApiInterface.kt
@Headers("Accept: application/json") @GET("/request") fun getInstituicoes(): Observable<Instituicao>
Instituicao.kt(实体)
data class Instituicao(val id: Int, val nome: String)
InstituicaoActivity ::列表视图
listView = ListView(this) setContentView(listView) instituicao = ArrayAdapter(this, android.R.layout.simple_list_item_1, instituicoes) listView?.adapter = instituicao var api = ApiClient() api.service.getInstituicoes() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ instituicao -> instituicoes.add("${instituicao.id} - ${instituicao.nome}") }, { e -> e.printStackTrace() }, { instituicao?.notifyDataSetChanged() }) }
结果:(
0-null
你的对象是这个
{"0": {"id":1,"nome":"teste"}
Gson希望只将这件作品作为一个对象进行解析
{"id":1,"nome":"teste"}
由于它不能,它已经返回null。
如果可能,您需要修复服务器代码以返回对象列表,而不是“索引映射”
服务器响应应该是
[ {"id":1,"nome":"teste"}, {"id":2,"nome":"teste 2"} ]
在修复服务器返回之后,Retrofit需要更新
Observable<List<Instituicao>>
如果这是不可能的,你需要研究为Gson制作自定义分析器,并在Retrofit中注册它们
(…或手动解析您的JSON)
- 如何从java测试代码访问内部属性
- Android Studio 3.0中的Plain Kotlin模块,`api`不支持?
- 片段内的Android SupportMapFragment
- Realm&Kotlin:DefaultRealmModuleMediator.java – > error:unreachable statement
- 只有在RecycleView / List大于屏幕的情况下,才能使用setStackFromEnd
- Android N中不赞成使用Html.fromHtml
- 如何动画动画列表在Kotlin?
- 房间不能选择一个构造函数,因为多个构造函数是合适的错误
- 浮动动作按钮不被禁用 – Kotlin