Я создаю приложение с 4 TabView, каждое представление которого является фрагментом с представлением переработчика в нем.Мне нужно выполнить запрос к API NewYorkTimes со списком «самых популярных» статей и сохранить его в соответствующих фрагментах.
Я уже пробовал разные варианты кода для этой задачи, но пока ничего не получилось
Заводской код API
object ApiFactory {
var BASE_URL: String = "https://api.nytimes.com/"
val getClient: NewsApi
get() {
val interceptor = HttpLoggingInterceptor()
val okhttp = OkHttpClient.Builder()
.addInterceptor { chain ->
var request = chain.request()
val url = request.url().newBuilder()
.addQueryParameter("api-key", "xPLvtKSHvG0f5alLcYJ79NQfyA0alh5S")
.addPathSegment("json")
.build()
request = request.newBuilder().url(url).build()
chain.proceed(request)
}
.addInterceptor(interceptor)
.build()
val gsonBuilder = GsonBuilder()
gsonBuilder.setLenient()
val gsonFactory = GsonConverterFactory.create(gsonBuilder.create())
return Retrofit.Builder()
.baseUrl(BASE_URL)
.client(okhttp)
.addConverterFactory(gsonFactory)
.build()
.create(NewsApi::class.java)
}
}
Интерфейс со спецификациями API
interface NewsApi {
@GET("svc/mostpopular/v2/emailed/7q")
fun getEmailedNews(): Response<NYTNewsResponse>
companion object {
var BASE_URL: String = "https://api.nytimes.com/"
fun getApi(): NewsApi {
var interceptor = HttpLoggingInterceptor()
val okhttp = OkHttpClient.Builder()
.addInterceptor { chain ->
var request = chain.request()
val url = request.url().newBuilder()
.addQueryParameter("api-key", "xPLvtKSHvG0f5alLcYJ79NQfyA0alh5S")
.addPathSegment("json")
.build()
request = request.newBuilder().url(url).build()
chain.proceed(request)
}
.addInterceptor(interceptor)
.build()
val gsonBuilder = GsonBuilder()
gsonBuilder.setLenient()
val gsonFactory = GsonConverterFactory.create(gsonBuilder.create())
return Retrofit.Builder()
.baseUrl(BASE_URL)
.client(okhttp)
.addConverterFactory(gsonFactory)
.build()
.create(NewsApi::class.java)
}
}
// @GET("shared/1/facebook")
//fun getSharedNews():Deferred<Response<NewsResponse>>
//@GET("viewed/1")
//fun getViewedNews():Deferred<Response<NewsResponse>>
}
Фрагмент с соответствующим вызовом
class EmailedFragment : Fragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
retainInstance=true
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_emailed, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val api = ApiFactory.getClient.getEmailedNews()?.body()
if (api!=null){
var mNews = api.results
emailed_list.apply {
adapter = NewsAdapter(mNews!!)
layoutManager = LinearLayoutManager(context)
}
}
else{ Toast.makeText(this.context,"fail",Toast.LENGTH_LONG).show()
val mNews = listOf(
NYTNewsItem("dsd", "dsds"),
NYTNewsItem("dsd", "dsds"),
NYTNewsItem("dsd", "dsds"),
NYTNewsItem("dsd", "dsds")
)
emailed_list.apply {
adapter = NewsAdapter(mNews!!)
layoutManager = LinearLayoutManager(context)
}
}
/*api.enqueue(object: Callback<NYTNewsResponse>{
override fun onResponse(call: Call<NYTNewsResponse>, response: Response<NYTNewsResponse>) {
if (response.body()!= null){
emailed_list.apply {
adapter = NewsAdapter(response.body().results.toList())
layoutManager = LinearLayoutManager(context)
}
}
}
override fun onFailure(call: Call<NYTNewsResponse>, t: Throwable) {
}
})*/
/*val mNews = listOf(
NYTNewsItem("dsd", "dsds"),
NYTNewsItem("dsd", "dsds"),
NYTNewsItem("dsd", "dsds"),
NYTNewsItem("dsd", "dsds")
)*/
}
companion object{
fun newInstance():EmailedFragment =EmailedFragment()
}
}
Actual errors: 2019-06-12 18:58:42.661 4502-4502/ru.minoro75.proj.kappatesting E/AndroidRuntime: FATAL EXCEPTION: main
Process: ru.minoro75.proj.kappatesting, PID: 4502
java.lang.BootstrapMethodError: Exception from call site #8 bootstrap method
at okhttp3.logging.HttpLoggingInterceptor$Logger.<clinit>(HttpLoggingInterceptor.java:112)
at okhttp3.logging.HttpLoggingInterceptor.<init>(HttpLoggingInterceptor.java:116)
at ru.minoro75.proj.kappatesting.networking.ApiFactory.getGetClient(ApiFactory.kt:19)
at ru.minoro75.proj.kappatesting.fragments.EmailedFragment.onViewCreated(EmailedFragment.kt:42)
````
:19 at apifactory is initialize of interceptor
val interceptor = HttpLoggingInterceptor()
:42 at emailedfragment is
val api = ApiFactory.getClient.getEmailedNews()?.body()