Загрузить с api список с помощью Retrofit
Уважаемые, умудренные опытом стекоуверфлоучане, вопрос: почему крашится приложение? понял, что с ссылкой что-то не так, а что именно понять не могу
class RetroInstance {
companion object {
private const val BASE_URL = "https://api.icndb.com/jokes/random/10/"
fun getRetroInstance(): Retrofit {
return Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
}
}
interface RetroServiceInterface {
@GET
fun getJokeList(): Call<List<JokeModel>>
}
class JokeListAdapter(val activity: Activity) : RecyclerView.Adapter<JokeListAdapter.MyViewHolder>(){
private var jokeList: List<JokeModel>? = null
fun setJokeList(jokeList: List<JokeModel>?){
this.jokeList = jokeList
}
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): JokeListAdapter.MyViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.joke_list_raw, parent, false)
return MyViewHolder(view)
}
override fun onBindViewHolder(holder: JokeListAdapter.MyViewHolder, position: Int) {
holder.bind(jokeList?.get(position)!!, activity)
}
override fun getItemCount(): Int {
if(jokeList == null) return 0
else return jokeList?.size!!
}
class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val jokeText = view.joke_text_view
fun bind(data: JokeModel, activity: Activity) {
jokeText.text = data.joke
}
}
}
class MainActivity : AppCompatActivity() {
lateinit var recyclerAdapter: JokeListAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
initRecyclerView()
initViewModel()
}
private fun initRecyclerView() {
jokeListRecyclerView.layoutManager = LinearLayoutManager(this)
recyclerAdapter = JokeListAdapter(this)
jokeListRecyclerView.adapter = recyclerAdapter
}
private fun initViewModel(){
val vieModel = ViewModelProvider(this).get(MainActivityViewModel::class.java)
vieModel.getLiveDataObserver().observe(this, Observer {
if (it != null){
recyclerAdapter.setJokeList(it)
recyclerAdapter.notifyDataSetChanged()
}else{
Toast.makeText(this, " Error is getting list", Toast.LENGTH_SHORT).show()
}
})
vieModel.makeApiCall()
}
}
В Logcat выдает вот такое
--------- beginning of crash 2021-09-14 14:35:30.322 7162-7162/com.example.chacknorrisfromapi
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.chacknorrisfromapi, PID: 7162
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.chacknorrisfromapi/com.example.chacknorrisfromapi.MainActivity}: java.lang.IllegalArgumentException: Missing either @GET URL or @Url parameter.
for method RetroServiceInterface.getJokeList
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Caused by: java.lang.IllegalArgumentException: Missing either @GET URL or @Url parameter.
for method RetroServiceInterface.getJokeList
at retrofit2.Utils.methodError(Utils.java:54)
at retrofit2.Utils.methodError(Utils.java:43)
at retrofit2.RequestFactory$Builder.build(RequestFactory.java:210)
at retrofit2.RequestFactory.parseAnnotations(RequestFactory.java:67)
at retrofit2.ServiceMethod.parseAnnotations(ServiceMethod.java:26)
at retrofit2.Retrofit.loadServiceMethod(Retrofit.java:202)
at retrofit2.Retrofit$1.invoke(Retrofit.java:160)
at java.lang.reflect.Proxy.invoke(Proxy.java:1006)
at $Proxy0.getJokeList(Unknown Source)
at com.example.chacknorrisfromapi.viewmodel.MainActivityViewModel.makeApiCall(MainActivityViewModel.kt:27)
at com.example.chacknorrisfromapi.MainActivity.initViewModel(MainActivity.kt:42)
at com.example.chacknorrisfromapi.MainActivity.onCreate(MainActivity.kt:22)
at android.app.Activity.performCreate(Activity.java:7825)
at android.app.Activity.performCreate(Activity.java:7814)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1306)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
... 11 more
2021-09-14 14:35:30.350 7162-7162/com.example.chacknorrisfromapi I/Process: Sending signal. PID: 7162 SIG: 9
Ответы (1 шт):
Автор решения: Andrew
→ Ссылка
У вас запрос GET а откуда вы это запрашиваете не указано:
@GET("endpoint_name")
fun getJokeList(): Call<List<JokeModel>>
в итоге у вас получится итоговый адрес:
"https://api.icndb.com/jokes/random/10/endpoint_name"
а сейчас у вас вероятнее всего запрос летел сюда:
"https://api.icndb.com/jokes/random/10/"
вот тут описано хорошо как работать с Retrofit2 на котлине. Либо укажите в качестве параметра к методу:
fun getJokeList(@Url url:String): Call<List<JokeModel>>