Reputation: 675
I'm using Retrofit 2.0 in my app. Everything was quite good, but when I started request with no args, GSON returns:
Unable to invoke no-args constructor for interface
com.example.project.API.GetPhones. Register an InstanceCreator
with Gson for this type may fix this problem.
Here's my API interface:
public interface GetPhones {
@GET("phones.php")
Call<ArrayList<GetPhones>> getPhones();
}
and model class:
public class GetPhones {
int id;
char[] iso;
String name;
String phone_1;
String phone_2;
String phone_3;
}
and code in fragment:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(URL_API)
.client(SSLSuppressClient.trustcert())
.addConverterFactory(GsonConverterFactory.create())
.build();
GetPhones getPhonesInfo = retrofit.create(GetPhones.class);
Call<GetPhones> call = getPhonesInfo.getPhones();
call.enqueue(new Callback<GetPhones>() {
@Override
public void onResponse(Response<GetPhones> response, Retrofit retrofit) {
Toast.makeText(getActivity(), "Success!", Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(Throwable t) {
Toast.makeText(getActivity(), "Failure!", Toast.LENGTH_SHORT).show();
Log.d("LOG", t.getMessage());
}
});
I've tried to make no-args constructor for GetPhones.class, but it doesn't change anything.
Upvotes: 12
Views: 10846
Reputation: 73
This was really helpful. I had the same issue and it worked by replacing Call<MyObject>
with MyObject
in the interface where we write the function for the API call request followed by removing .enque
at the call site.
Upvotes: 1
Reputation: 19824
If anyone in 2019 comes across this and is using Kotlin, coroutines and at least Retrofit 2.6.0, returning a Call<MyObject>
instance while the api method is suspended
, produces the same error message, which is a little confusing.
The solution is to replace Call<MyObject>
with MyObject
in the interface definition, and remove ?.execute()?.body()
(or equivalent) at the call site.
EDIT:
The reason I think most people will stumble across this is that they want to wrap their suspended Retrofit responses in something to handle errors in a seamless way.
There is an issue on this located here, perhaps Retrofit will deal with this in the future. I ended up using the kind solution provided here.
Upvotes: 53
Reputation: 7010
You have the same name for interface (interface GetPhones
) and model class (class GetPhones
).
I think you are using interface in this line:
Call<ArrayList<GetPhones>> getPhones();
But it should be your model class. Check import section for it or rename model class to be sure that you are not mixing it.
Upvotes: 4