このチュートリアルに従って、JSON を取得し、Retrofit と GSON を使用して POJO にシリアル化しています。すべてが正しく機能しています。インスタンスを SQLite データベースに保存するために、Sugar ORM を使用しました。私のPOJOにはフィールドがあります-整数ID。
@Generated("org.jsonschema2pojo")
public class Item extends SugarRecord{
@SerializedName("login")
@Expose
private String login;
@SerializedName("id")
@Expose
private Long id;
Sugar ORM では、Integer id が Long である必要があります。私はオーケーと言ってロングにしました。アプリを実行すると、次のエラーが発生します。
01-18 06:03:44.436 4498-4498/uz.cp.retrofitsandbox E/AndroidRuntime: 致命的な例外: メイン プロセス: uz.cp.retrofitsandbox、PID: 4498 java.lang.RuntimeException: アクティビティ ComponentInfo{uz を開始できません。 cp.retrofitsandbox/uz.cp.retrofitsandbox.MainActivity}: java.lang.IllegalArgumentException: android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298) android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360) で android.app.ActivityThread.access$800(ActivityThread.java:144) で android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278) android.os.Handler.dispatchMessage(Handler.java:102) で android.os.Looper.loop(Looper.java:135) で android.app.ActivityThread.main(ActivityThread.java:5221) com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit. java:899) com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) 原因: java.lang.IllegalArgumentException: メソッド GitApiInterface のクラス uz.cp.retrofitsandbox.GitResult のコンバーターを作成できません。getUsersNamedTom で retrofit.Utils.methodError(Utils.java:201) で retrofit.MethodHandler.createResponseConverter(MethodHandler.java:67) で retrofit.MethodHandler.create(MethodHandler.java:32) で retrofit.Retrofit.loadMethodHandler(Retrofit.java) :138) retrofit.Retrofit$1.invoke(Retrofit.java:127) で java.lang.reflect.Proxy.invoke(Proxy.java:397) android.app.Instrumentation. callActivityOnCreate(Instrumentation.java:1105) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251) ...10 以上の原因: java.lang.IllegalArgumentException: クラス uz.cp.retrofitsandbox.Item は、com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:146) で id という名前の複数の JSON フィールドを com.google で宣言します.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:83) at com.google.gson.Gson.getAdapter(Gson.java:359) at com.google.gson.internal.bind.CollectionTypeAdapterFactory.create(CollectionTypeAdapterFactory.java:52) com.google.gson.Gson.getAdapter(Gson.java:359) com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getFieldAdapter(ReflectiveTypeAdapterFactory.java:122) で com.google .gson.internal.bind.ReflectiveTypeAdapterFactory.access$100(ReflectiveTypeAdapterFactory.java:46) at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.(ReflectiveTypeAdapterFactory.java:92) at com.google.gson.internal.bind.com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:142) の ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:91) com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java: 83) com.google.gson.Gson.getAdapter(Gson.java:359) で retrofit.GsonConverterFactory.get(GsonConverterFactory.java:50) で retrofit.Utils.resolveConverter(Utils.java:72) retrofit.MethodHandler.createResponseConverter(MethodHandler.java:65) で ... 19 もっと見る
このエラーは、次の行に誘導しています(27):
Call<GitResult> call = service.getUsersNamedTom("tom");
私の質問: なぜこのエラーが発生するのですか? これを解決するには?
build.gradle(アプリ)
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
applicationId "uz.cp.retrofitsandbox"
minSdkVersion 9
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.squareup.retrofit:retrofit:2.0.0-beta1'
compile 'com.squareup.okhttp:okhttp:2.4.0'
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta1'
compile 'org.glassfish.main:javax.annotation:4.0-b33'
compile 'com.github.satyan:sugar:1.4'
}
onCreate(MainActivity.java):
String baseUrl = "https://api.github.com" ;
Retrofit client = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
GitApiInterface service = client.create(GitApiInterface.class);
Call<GitResult> call = service.getUsersNamedTom("tom");
call.enqueue(new Callback<GitResult>() {
@Override
public void onResponse(Response<GitResult> response) {
if (response.isSuccess()) {
GitResult result = response.body();
result.save();
GitResult gitResult = GitResult.first(GitResult.class);
Toast.makeText(getApplicationContext(), String.valueOf(gitResult.getItems().size()), Toast.LENGTH_LONG).show();
} else {
//request not successful (like 400,401,403 etc)
//Handle errors
}
}
@Override
public void onFailure(Throwable t) {
}
});
GitApiInterface.java
package uz.cp.retrofitsandbox;
import retrofit.Call;
import retrofit.http.Body;
import retrofit.http.GET;
import retrofit.http.POST;
import retrofit.http.PUT;
import retrofit.http.Path;
import retrofit.http.Query;
/**
* Created by Joe on 1/18/2016.
*/
public interface GitApiInterface {
@GET("/search/users")
Call<GitResult> getUsersNamedTom(@Query("q") String name);
@POST("/user/create")
Call<Item> createUser(@Body String name, @Body String email);
@PUT("/user/{id}/update")
Call<Item> updateUser(@Path("id") String id , @Body Item user);
}
GitResult.java
package uz.cp.retrofitsandbox;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import com.orm.SugarRecord;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Generated;
@Generated("org.jsonschema2pojo")
public class GitResult extends SugarRecord{
@SerializedName("total_count")
@Expose
private Integer totalCount;
@SerializedName("incomplete_results")
@Expose
private Boolean incompleteResults;
@SerializedName("items")
@Expose
private List<Item> items = new ArrayList<Item>();
/**
* No args constructor for use in serialization
*
*/
public GitResult() {
}
/**
*
* @param items
* @param totalCount
* @param incompleteResults
*/
public GitResult(Integer totalCount, Boolean incompleteResults, List<Item> items) {
this.totalCount = totalCount;
this.incompleteResults = incompleteResults;
this.items = items;
}
/**
*
* @return
* The totalCount
*/
public Integer getTotalCount() {
return totalCount;
}
/**
*
* @param totalCount
* The total_count
*/
public void setTotalCount(Integer totalCount) {
this.totalCount = totalCount;
}
/**
*
* @return
* The incompleteResults
*/
public Boolean getIncompleteResults() {
return incompleteResults;
}
/**
*
* @param incompleteResults
* The incomplete_results
*/
public void setIncompleteResults(Boolean incompleteResults) {
this.incompleteResults = incompleteResults;
}
/**
*
* @return
* The items
*/
public List<Item> getItems() {
return items;
}
/**
*
* @param items
* The items
*/
public void setItems(List<Item> items) {
this.items = items;
}
}
アイテム.java
package uz.cp.retrofitsandbox;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import com.orm.SugarRecord;
import javax.annotation.Generated;
@Generated("org.jsonschema2pojo")
public class Item extends SugarRecord{
@SerializedName("login")
@Expose
private String login;
@SerializedName("id")
@Expose
private Long id;
@SerializedName("avatar_url")
@Expose
private String avatarUrl;
@SerializedName("gravatar_id")
@Expose
private String gravatarId;
@SerializedName("url")
@Expose
private String url;
@SerializedName("html_url")
@Expose
private String htmlUrl;
@SerializedName("followers_url")
@Expose
private String followersUrl;
@SerializedName("following_url")
@Expose
private String followingUrl;
@SerializedName("gists_url")
@Expose
private String gistsUrl;
@SerializedName("starred_url")
@Expose
private String starredUrl;
@SerializedName("subscriptions_url")
@Expose
private String subscriptionsUrl;
@SerializedName("organizations_url")
@Expose
private String organizationsUrl;
@SerializedName("repos_url")
@Expose
private String reposUrl;
@SerializedName("events_url")
@Expose
private String eventsUrl;
@SerializedName("received_events_url")
@Expose
private String receivedEventsUrl;
@SerializedName("type")
@Expose
private String type;
@SerializedName("site_admin")
@Expose
private Boolean siteAdmin;
@SerializedName("score")
@Expose
private Double score;
/**
* No args constructor for use in serialization
*
*/
public Item() {
}
/**
*
* @param eventsUrl
* @param siteAdmin
* @param gistsUrl
* @param score
* @param type
* @param gravatarId
* @param url
* @param subscriptionsUrl
* @param id
* @param followersUrl
* @param reposUrl
* @param htmlUrl
* @param receivedEventsUrl
* @param avatarUrl
* @param followingUrl
* @param login
* @param organizationsUrl
* @param starredUrl
*/
public Item(String login, Long id, String avatarUrl, String gravatarId, String url, String htmlUrl, String followersUrl, String followingUrl, String gistsUrl, String starredUrl, String subscriptionsUrl, String organizationsUrl, String reposUrl, String eventsUrl, String receivedEventsUrl, String type, Boolean siteAdmin, Double score) {
this.login = login;
this.id = id;
this.avatarUrl = avatarUrl;
this.gravatarId = gravatarId;
this.url = url;
this.htmlUrl = htmlUrl;
this.followersUrl = followersUrl;
this.followingUrl = followingUrl;
this.gistsUrl = gistsUrl;
this.starredUrl = starredUrl;
this.subscriptionsUrl = subscriptionsUrl;
this.organizationsUrl = organizationsUrl;
this.reposUrl = reposUrl;
this.eventsUrl = eventsUrl;
this.receivedEventsUrl = receivedEventsUrl;
this.type = type;
this.siteAdmin = siteAdmin;
this.score = score;
}
/**
*
* @return
* The login
*/
public String getLogin() {
return login;
}
/**
*
* @param login
* The login
*/
public void setLogin(String login) {
this.login = login;
}
/**
*
* @return
* The id
*/
public Long getId() {
return id;
}
/**
*
* @param id
* The id
*/
public void setId(Long id) {
this.id = id;
}
/**
*
* @return
* The avatarUrl
*/
public String getAvatarUrl() {
return avatarUrl;
}
/**
*
* @param avatarUrl
* The avatar_url
*/
public void setAvatarUrl(String avatarUrl) {
this.avatarUrl = avatarUrl;
}
/**
*
* @return
* The gravatarId
*/
public String getGravatarId() {
return gravatarId;
}
/**
*
* @param gravatarId
* The gravatar_id
*/
public void setGravatarId(String gravatarId) {
this.gravatarId = gravatarId;
}
/**
*
* @return
* The url
*/
public String getUrl() {
return url;
}
/**
*
* @param url
* The url
*/
public void setUrl(String url) {
this.url = url;
}
/**
*
* @return
* The htmlUrl
*/
public String getHtmlUrl() {
return htmlUrl;
}
/**
*
* @param htmlUrl
* The html_url
*/
public void setHtmlUrl(String htmlUrl) {
this.htmlUrl = htmlUrl;
}
/**
*
* @return
* The followersUrl
*/
public String getFollowersUrl() {
return followersUrl;
}
/**
*
* @param followersUrl
* The followers_url
*/
public void setFollowersUrl(String followersUrl) {
this.followersUrl = followersUrl;
}
/**
*
* @return
* The followingUrl
*/
public String getFollowingUrl() {
return followingUrl;
}
/**
*
* @param followingUrl
* The following_url
*/
public void setFollowingUrl(String followingUrl) {
this.followingUrl = followingUrl;
}
/**
*
* @return
* The gistsUrl
*/
public String getGistsUrl() {
return gistsUrl;
}
/**
*
* @param gistsUrl
* The gists_url
*/
public void setGistsUrl(String gistsUrl) {
this.gistsUrl = gistsUrl;
}
/**
*
* @return
* The starredUrl
*/
public String getStarredUrl() {
return starredUrl;
}
/**
*
* @param starredUrl
* The starred_url
*/
public void setStarredUrl(String starredUrl) {
this.starredUrl = starredUrl;
}
/**
*
* @return
* The subscriptionsUrl
*/
public String getSubscriptionsUrl() {
return subscriptionsUrl;
}
/**
*
* @param subscriptionsUrl
* The subscriptions_url
*/
public void setSubscriptionsUrl(String subscriptionsUrl) {
this.subscriptionsUrl = subscriptionsUrl;
}
/**
*
* @return
* The organizationsUrl
*/
public String getOrganizationsUrl() {
return organizationsUrl;
}
/**
*
* @param organizationsUrl
* The organizations_url
*/
public void setOrganizationsUrl(String organizationsUrl) {
this.organizationsUrl = organizationsUrl;
}
/**
*
* @return
* The reposUrl
*/
public String getReposUrl() {
return reposUrl;
}
/**
*
* @param reposUrl
* The repos_url
*/
public void setReposUrl(String reposUrl) {
this.reposUrl = reposUrl;
}
/**
*
* @return
* The eventsUrl
*/
public String getEventsUrl() {
return eventsUrl;
}
/**
*
* @param eventsUrl
* The events_url
*/
public void setEventsUrl(String eventsUrl) {
this.eventsUrl = eventsUrl;
}
/**
*
* @return
* The receivedEventsUrl
*/
public String getReceivedEventsUrl() {
return receivedEventsUrl;
}
/**
*
* @param receivedEventsUrl
* The received_events_url
*/
public void setReceivedEventsUrl(String receivedEventsUrl) {
this.receivedEventsUrl = receivedEventsUrl;
}
/**
*
* @return
* The type
*/
public String getType() {
return type;
}
/**
*
* @param type
* The type
*/
public void setType(String type) {
this.type = type;
}
/**
*
* @return
* The siteAdmin
*/
public Boolean getSiteAdmin() {
return siteAdmin;
}
/**
*
* @param siteAdmin
* The site_admin
*/
public void setSiteAdmin(Boolean siteAdmin) {
this.siteAdmin = siteAdmin;
}
/**
*
* @return
* The score
*/
public Double getScore() {
return score;
}
/**
*
* @param score
* The score
*/
public void setScore(Double score) {
this.score = score;
}
}