数据的加载
- 官网上推荐了一个Moshi解析json的库,它是一个 Android JSON 解析器,可将 JSON 字符串转换为 Kotlin 对象。Retrofit 有一个可与 Moshi 配合使用的转换器,所以这里使用了moshi。
implementation "com.squareup.retrofit2:retrofit:$version_retrofit"
implementation "com.squareup.retrofit2:converter-moshi:$version_retrofit"
implementation "com.squareup.moshi:moshi-kotlin:$version_moshi"
- Moshi官方除了介绍它是专门针对kotlin解析json的库外,它的使用方法,和常用的gson或JSONObject类似,它默认根据json的参数名称来匹配bean中的属性名,你也可以指定
data class MarData (
val id: String,
@Json(name = "img_src") val img_src: String,
val type: String,
val price: Double
)
const val BASE_URL = "https://android-kotlin-fun-mars-server.appspot.com"
...
interface ApiServer {
@GET("realestate")
fun getProperties(): Call<List<MarData>>
}
- 构建Retrofit对象,和接收到数据后,通知viewModel进行更新,这里用的Adapter还是官网推荐的ListAdapter。
open class BaseNetUtil {
private var moshi:Moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
private var retrofit:Retrofit
init {
retrofit = Retrofit.Builder()
.addConverterFactory(MoshiConverterFactory.create(moshi))
.baseUrl(Parameter.BASE_URL)
.build()
}
private val retrofitService: ApiServer by lazy { retrofit.create(ApiServer::class.java)}
fun getMarData(data : MutableLiveData<List<MarData>>){
retrofitService.getProperties().enqueue(object : Callback<List<MarData>> {
override fun onResponse(call: Call<List<MarData>>, response: Response<List<MarData>>) {
data.postValue(response.body())
}
override fun onFailure(call: Call<List<MarData>>, c: Throwable) {
}
})
}
}
private fun addData(owner:LifecycleOwner) {
viewModelScope.launch(Dispatchers.IO){
BaseNetUtil().getMarData(data)
}
data.observe(owner, Observer {
adapter.submitList(it as MutableList<MarData>)
})
}
- 有一点需要注意的是,retrofit安装之后是需要分包,所以添加了依赖和初始化,并且还需要指定是java8
MultiDex.install(this);
multiDexEnabled true
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
implementation 'com.android.support:multidex:1.0.3'
- 最后强调一点,这个数据看域名就知道是US的,所以正常情况下国内是访问不到的。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9uLEqD4j-1626337077376)(media/16260614201077/16263148673142.jpg)]
Glide.with(imgView.context)
.load(imgUri)
.apply(RequestOptions()
.placeholder(R.drawable.loading_animation)
.error(R.drawable.ic_broken_image))
.into(imgView)