簡體   English   中英

使用翻新從api獲取響應的api獲取響應中的錯誤

[英]error in get response from api using retrofit to fetch it in recycleview

我正在嘗試與此API聯網: https//api.jikan.moe/v3/schedule

所以我通過創建ApiClient.java類使用改造,這是它的代碼:

public class ApiClient {

public static final String BASE_URL = "http://api.themoviedb.org/3/";
private static Retrofit retrofit = null;

public static Retrofit getClient() {
    if (retrofit==null) {
        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    return retrofit;
}

}

鏈接的完整端點的接口是這樣的:

public interface ApiInterface {

    @GET("schedule")
    Call<MainResponse> getSchedule();

}

因此,我在數據建模中使用了可序列化的代碼,並創建了MainResponse.java類來獲取api中的主要星期一數組:

公共類MainResponse {

@SerializedName("monday")
private List<Schedule> monday;

public List<Schedule> getMonday() {
    return monday;
}

public void setMonday(List<Schedule> monday) {
    this.monday = monday;
}

}

然后創建一個新的建模類,以在Schedule.java類中獲取monday數組的對象項列表:

public class Schedule {

    @SerializedName("title")
    private String title;

    public Schedule(String title) {
        this.title = title;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
}

最后在MainActivity中,我將其稱為:

final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.schedule_recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        ApiInterface apiService =
                ApiClient.getClient().create(ApiInterface.class);

        Call<MainResponse> call = apiService.getSchedule();
        call.enqueue(new Callback<MainResponse>() {
            @Override
            public void onResponse(Call<MainResponse> call, Response<MainResponse> response) {
                int statusCode = response.code();
                List<Schedule> schedule = response.body().getMonday();
                recyclerView.setAdapter(new MainAdapter(schedule, R.layout.list_item_schedule, getApplicationContext()));
            }

            @Override
            public void onFailure(Call<MainResponse> call, Throwable t) {
                // Log error here since request failed
                Log.e(TAG, t.toString());
            }
        });

如您所見,我使用了recycleview來獲取星期一數組的標題,但是問題是當我運行應用程序時,它由於以下原因而被壓碎了:

嘗試在空對象引用上調用虛擬方法'java.util.List com.example.user_pc.capstonestage2.MainResponse.getMonday()'

這是整個錯誤對話框:

10-14 20:53:45.462 1050-1050/com.example.user_pc.capstonestage2 E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.user_pc.capstonestage2, PID: 1050
    java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.List com.example.user_pc.capstonestage2.MainResponse.getMonday()' on a null object reference
        atcom.example.user_pc.capstonestage2.MainActivity$1.onResponse(MainActivity.java:36)
        at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6682)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)

我不明白為什么它為空

我也在logcat中發現了此錯誤:

10-14 21:02:12.373 9046-9046 / com.example.user_pc.capstonestage2 E / RecyclerView:未連接適配器; 跳過布局

因此,如果您需要適配器的代碼,就是這樣:

public class MainAdapter extends RecyclerView.Adapter<MainAdapter.MovieViewHolder> {

    private List<Schedule> schedule;
    private int rowLayout;
    private Context context;


    public static class MovieViewHolder extends RecyclerView.ViewHolder {
        LinearLayout schedulesLayout;
        TextView title;


        public MovieViewHolder(View v) {
            super(v);
            schedulesLayout = (LinearLayout) v.findViewById(R.id.schedule_layout);
            title = (TextView) v.findViewById(R.id.title);

        }
    }

    public MainAdapter(List<Schedule> schedule, int rowLayout, Context context) {
        this.schedule = schedule;
        this.rowLayout = rowLayout;
        this.context = context;
    }

    @Override
    public MainAdapter.MovieViewHolder onCreateViewHolder(ViewGroup parent,
                                                            int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(rowLayout, parent, false);
        return new MovieViewHolder(view);
    }


    @Override
    public void onBindViewHolder(MovieViewHolder holder, final int position) {
        holder.title.setText(schedule.get(position).getTitle());
    }

    @Override
    public int getItemCount() {
        return schedule.size();
    }
}

您已聲明錯誤的API URL為:

public static final String BASE_URL = "https://api.jikan.moe/v3/";

您的MainResponse應該是這樣的:

public class MainResponse {

@SerializedName("request_hash")
@Expose
private String requestHash;
@SerializedName("request_cached")
@Expose
private Boolean requestCached;
@SerializedName("request_cache_expiry")
@Expose
private Integer requestCacheExpiry;
@SerializedName("monday")
@Expose
private List<Monday> monday = null;

public String getRequestHash() {
return requestHash;
}

public void setRequestHash(String requestHash) {
this.requestHash = requestHash;
}

public Boolean getRequestCached() {
return requestCached;
}

public void setRequestCached(Boolean requestCached) {
this.requestCached = requestCached;
}

public Integer getRequestCacheExpiry() {
return requestCacheExpiry;
}

public void setRequestCacheExpiry(Integer requestCacheExpiry) {
this.requestCacheExpiry = requestCacheExpiry;
}

public List<Monday> getMonday() {
return monday;
}

public void setMonday(List<Monday> monday) {
this.monday = monday;
}

}

Genre

public class Genre {

@SerializedName("mal_id")
@Expose
private Integer malId;
@SerializedName("type")
@Expose
private String type;
@SerializedName("name")
@Expose
private String name;
@SerializedName("url")
@Expose
private String url;

public Integer getMalId() {
return malId;
}

public void setMalId(Integer malId) {
this.malId = malId;
}

public String getType() {
return type;
}

public void setType(String type) {
this.type = type;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getUrl() {
return url;
}

public void setUrl(String url) {
this.url = url;
}

}

最后是Monday

public class Monday {

@SerializedName("mal_id")
@Expose
private Integer malId;
@SerializedName("url")
@Expose
private String url;
@SerializedName("title")
@Expose
private String title;
@SerializedName("image_url")
@Expose
private String imageUrl;
@SerializedName("synopsis")
@Expose
private String synopsis;
@SerializedName("type")
@Expose
private String type;
@SerializedName("airing_start")
@Expose
private String airingStart;
@SerializedName("episodes")
@Expose
private Integer episodes;
@SerializedName("members")
@Expose
private Integer members;
@SerializedName("genres")
@Expose
private List<Genre> genres = null;
@SerializedName("source")
@Expose
private String source;
@SerializedName("producers")
@Expose
private List<Object> producers = null;
@SerializedName("score")
@Expose
private Object score;
@SerializedName("licensors")
@Expose
private List<Object> licensors = null;
@SerializedName("r18")
@Expose
private Boolean r18;
@SerializedName("kids")
@Expose
private Boolean kids;

public Integer getMalId() {
return malId;
}

public void setMalId(Integer malId) {
this.malId = malId;
}

public String getUrl() {
return url;
}

public void setUrl(String url) {
this.url = url;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public String getImageUrl() {
return imageUrl;
}

public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}

public String getSynopsis() {
return synopsis;
}

public void setSynopsis(String synopsis) {
this.synopsis = synopsis;
}

public String getType() {
return type;
}

public void setType(String type) {
this.type = type;
}

public String getAiringStart() {
return airingStart;
}

public void setAiringStart(String airingStart) {
this.airingStart = airingStart;
}

public Integer getEpisodes() {
return episodes;
}

public void setEpisodes(Integer episodes) {
this.episodes = episodes;
}

public Integer getMembers() {
return members;
}

public void setMembers(Integer members) {
this.members = members;
}

public List<Genre> getGenres() {
return genres;
}

public void setGenres(List<Genre> genres) {
this.genres = genres;
}

public String getSource() {
return source;
}

public void setSource(String source) {
this.source = source;
}

public List<Object> getProducers() {
return producers;
}

public void setProducers(List<Object> producers) {
this.producers = producers;
}

public Object getScore() {
return score;
}

public void setScore(Object score) {
this.score = score;
}

public List<Object> getLicensors() {
return licensors;
}

public void setLicensors(List<Object> licensors) {
this.licensors = licensors;
}

public Boolean getR18() {
return r18;
}

public void setR18(Boolean r18) {
this.r18 = r18;
}

public Boolean getKids() {
return kids;
}

public void setKids(Boolean kids) {
this.kids = kids;
}

}

您的api鏈接為https://api.jikan.moe/v3/schedule,但是在您編寫的代碼中

public static final String BASE_URL = "http://api.themoviedb.org/3/";

您可以將基本URL更改為https://api.jikan.moe/v3/ ,或者
提供有關getSchedule()的GET注釋的完整URL

 @GET("https://api.jikan.moe/v3/schedule")
 Call<MainResponse> getSchedule();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM