【发布时间】:2021-05-04 00:51:33
【问题描述】:
我正在使用改造向 API 发出网络请求。响应代码返回 200,但我在尝试访问字段时收到 null。我已经检查了其他解决方案,但似乎无法解决我的问题。我正在使用hilt
这是我的 API 类
interface BlockIOApi{
@GET("/api/v2/get_balance/")
suspend fun getBalance(
@Query("api_key")
apiKey: String = BuildConfig.API_KEY
): Response<BalanceResponse>
}
这是我的应用模块对象
应用模块
@Module
@InstallIn(ApplicationComponent::class)
object AppModule{
@Singleton
@Provides
fun provideOkHttpClient() = if (BuildConfig.DEBUG) {
val loggingInterceptor = HttpLoggingInterceptor()
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
OkHttpClient.Builder()
.addInterceptor(loggingInterceptor)
.build()
} else OkHttpClient
.Builder()
.build()
@Provides
@Singleton
fun providesRetrofit(okHttpClient: OkHttpClient): Retrofit =
Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(BASE_URL)
.client(okHttpClient)
.build()
@Provides
@Singleton
fun providesApiService(retrofit: Retrofit): BlockIOApi = retrofit.create(BlockIOApi::class.java)
}
最后是我的存储库,DefaultRepository.kt
class DefaultRepository @Inject constructor(
private val blockIOApi: BlockIOApi,
private val balanceDao: BalanceDao
):BlockIORepository {
override suspend fun getBalance(): Resource<BalanceResponse> {
return try {
val response = blockIOApi.getBalance()
Log.d("TAG", "getBalance>>Response:${response.body()?.balance} ")
if (response.isSuccessful){
response.body().let {
return@let Resource.success(it)
}
}else{
Log.d("TAG", "getBalance: Error Response >>> ${response.message()}")
Resource.error("An unknown error occured",null)
}
}catch (ex :Exception){
Resource.error("Could not reach the server.Check your internet connection",null)
}
}
还有这个接口,BlockIORepository.kt
interface BlockIORepository {
suspend fun getBalance(): Resource<BalanceResponse>
suspend fun insertBalance(balance: Balance)
suspend fun getCachedBalance(): Balance
suspend fun getAddresses(): Resource<DataX>
}
这是我的数据类
data class BalanceResponse(
val balance: Balance,
val status: String
)
@Entity
data class Balance(
val available_balance: String,
val network: String,
val pending_received_balance: String,
@PrimaryKey(autoGenerate = false)
var id: Int? = null
)
当我尝试访问 data 对象时,问题就来了。 status 对象我没有得到 null
我已经坚持了两天了。任何帮助将不胜感激。提前致谢。
【问题讨论】:
-
receive null when accessing field是什么意思?值是返回 null 吗? -
它返回一个空值。但是响应代码是 200
-
你和邮递员核实了吗?返回的结果有价值吗?因为如果结果与你的 POJO 不匹配,改造会抛出异常
-
我已经更新了这个问题。尝试访问第二个对象
data时会出现问题。我已经发布了上面的截图 -
你能把你的数据类
BalanceResponse一起发帖吗?
标签: android kotlin mvvm retrofit2 dagger-hilt