我正在尝试从android应用程序中的api获取数据。我正在使用Kotlin,Retrofit2,rxjava,viewmodel和dagger。这不会在api上进行任何调用,也不会引发任何错误。
这是我的JSON,将在成功调用后收到。
{"data":[{"uid":"bf167b90-e8a0-41b6-aac2-71d305a3f41a",
"title":"category 1",
"image":""}],
"status":{"code":105,"msg":"categories data"}}
这是我的数据类
@Entity(tableName="categories")
data class Category(@PrimaryKey(autoGenerate = true) var id: Long?,
@ColumnInfo(name = "remote_id") var remoteID: String,
@ColumnInfo(name = "title") var title:String,
@ColumnInfo(name = "parent") var parent: String,
@ColumnInfo(name = "status") var status: String,
@ColumnInfo(name = "created_at") var createdAt: String,
@ColumnInfo(name = "created_by") var createdBy: String) {
constructor():this(null,"","","","","",
"")
}
data class CategoryResult(val status: Status, val data:
List<CategoryJSON>)
data class Status(val code:String, val msg:String)
data class CategoryJSON(val uid: String, val title: String, val
image:String)
这是我的服务接口代码。
interface PMAPI {
@GET("category")
fun getCategories(): Observable<CategoryResult>
@GET("category")
fun getTasks(): Observable<List<Task>>
}
匕首注射
@Provides
@Singleton
fun provideHttpCache(application: Application): Cache {
val cacheSize = 10 * 1024 * 1024
return Cache(application.cacheDir, cacheSize.toLong())
}
@Provides
@Singleton
fun provideGson(): Gson {
val gsonBuilder = GsonBuilder()
gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
return gsonBuilder.create()
}
@Provides
@Singleton
fun provideOkhttpClient(cache: Cache): OkHttpClient {
val interceptor = HttpLoggingInterceptor()
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
val client = OkHttpClient.Builder()
client.cache(cache)
client.addInterceptor(interceptor)
return client.build()
}
@Provides
@Singleton
fun provideRetrofit(gson: Gson, okHttpClient: OkHttpClient): Retrofit {
return Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.baseUrl(mBaseUrl)
.client(okHttpClient)
.build()
}
@Provides
@Singleton
fun providePMAPI(retrofit: Retrofit): PMAPI {
return retrofit.create(PMAPI::class.java)
}
存储库
fun getCategoriesFromApi(): Observable<List<Category>> {
Log.d("Category Repository", "Getting Categories from Api")
var categoryResult = api.getCategories()
var categories = mutableListOf<Category>()
categoryResult.doOnNext {
Log.d("Category Repository","Dispatching categories from API...")
it.data.forEach {
var category = Category()
category.remoteID = it.uid
category.title = it.title
categories.add(category)
}
storeProjectsInDb(categories)
}
return Observable.fromArray(categories)
}