3

I am trying to create a simple News app with the following endpoint:

https://content.guardianapis.com/search?api-key=...&show-fields=thumbnail&show-blocks=body&type=article

I know there are 2-3 questions already on SO about this but I belive that this exception is unique since it can not create a constructor for a library interace?!...

Here are my project files:

Retrofit client

Model classes

Custom adapter and activity

I get the following RuntimeException when trying to call

call.enqueue(new Callback<News>() {

In the main activity:

Unable to invoke no-args constructor for interface retrofit2.http.Body. Registering an InstanceCreator with Gson for this type may fix this problem.

So far I have tried:

  • Creating no-arg constructors for each of my model classes as mentioned in another similar question

  • Checking whether the any of the classes share similar names with the retrofit interace as mentioned here and here

Any idea what could cause this? I belive my code should be working and since the error is with a the retrofit2.http.Body interface which to my knowledge I should not have to implement anywhere...

I really appreciate any form of help! Thanks!

1 Answers1

1

The Blocks model you have doesn't import the correct Body type.

All you have to do is remove the following line:

import retrofit2.http.Body;

This way your model will use the Body class from the same package.

Egor Neliuba
  • 14,784
  • 7
  • 59
  • 77
  • 1
    Thank you so much! That fixed it and the API call works flawessly! May I ask, as someone who spent hours trying to figure this out: What led you to find this solution? I genuinely want to get better at this :P – rolandsarosy Jul 22 '18 at 18:25
  • @Augmentum the Gson library is responsible for deserializing JSON into Java classes. In order to do it, it instantiates the necessary classes (models) using the no-args constructor and then using reflection it writes the correct values into fields. Now, the "Unable to invoke no-args constructor for interface retrofit2.http.Body" error is from Gson and it tells us that one of the models is or contains a field of this type. – Egor Neliuba Jul 22 '18 at 19:10
  • I see. Thanks for the detailed explanation, it makes much more sense now :) – rolandsarosy Jul 23 '18 at 19:14