Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

java - Retrofit 2.0 + GSON Unable to invoke no-args constructor for interface

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...