无法使用Retrofit调用GItHub搜索用户API。

问题描述 投票:0回答:1

我正在试验 GitHub搜索用户API. 我的目标是写一个简单的应用:输入一个用户名,任何与之相关的GitHub用户名都会显示在RecyclerView上(使用MVVM模式)。

例如,以下是搜索用户名的方法 崖壁:

https://api.github.com/search/users?q=clive

这里是相关的代码部分。

APIConfig.java

public class APIConfig {

    public static final String BASE_URL = "https://api.github.com";
    public static final String END_POINT_SEARCH_USERS = "/search/users";

}

APIEndPoint.java

import com.divbyzero.app.githubusersearch.model.User;

import java.util.List;

import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;

public interface APIEndPoint {

    @GET(APIConfig.END_POINT_SEARCH_USERS)
    Call<List<User>> getSearchResult(@Query("q") String param);

}

用户.java

    package com.divbyzero.app.githubusersearch.model;

    import com.google.gson.annotations.Expose;
    import com.google.gson.annotations.SerializedName;

    public class User {

        @SerializedName("login")
        @Expose
        private String login;

        @SerializedName("avatar_url")
        @Expose
        private String avatar_url;

        public void setLogin(String login){
            this.login = login;
        }

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

        public String getLogin(){
            return login;
        }

        public String getAvatarUrl(){
            return avatar_url;
        }

        public User(String login, String url){
            this.login = login;
            this.avatar_url = url;
        }
    }

UserViewModel.java

  package com.divbyzero.app.githubusersearch.viewmodel;

    import android.util.Log;

    import androidx.lifecycle.LiveData;
    import androidx.lifecycle.MutableLiveData;
    import androidx.lifecycle.ViewModel;

    import com.divbyzero.app.githubusersearch.api.APIEndPoint;
    import com.divbyzero.app.githubusersearch.api.APIService;
    import com.divbyzero.app.githubusersearch.model.User;

    import java.util.ArrayList;
    import java.util.List;

    import retrofit2.Call;
    import retrofit2.Callback;
    import retrofit2.Response;
    import retrofit2.Retrofit;

    public class UserViewModel extends ViewModel {

        private MutableLiveData<ArrayList<User>> mutableLiveData = new MutableLiveData<>();

        public void setSearchResult(String param){
            Retrofit retrofit = APIService.getRetrofitService();
            APIEndPoint apiEndpoint = retrofit.create(APIEndPoint.class);
            Call<List<User>> call = apiEndpoint.getSearchResult(param);
            call.enqueue(new Callback<List<User>>() {
                @Override
                public void onResponse(Call<List<User>> call, Response<List<User>> response) {
                    mutableLiveData.setValue((ArrayList<User>) response.body());
                    Log.d("DBG", "OK");
                }

                @Override
                public void onFailure(Call<List<User>> call, Throwable t) {
                    Log.d("DBG", "Failed");
                }
            });
        }

        public LiveData<ArrayList<User>> getSearchResult(){
            return mutableLiveData;
        }
    }

完整的源代码。https:/github.comanta40GithubUserSearch。

当我在SearchView上输入任意用户名并按下ENTER键时,没有显示任何搜索结果(recyclerview还是空的)。经过进一步检查,我发现在logcat上显示 "DBG: Failed",这意味着GitHub API没有被正确调用。如何解决这个问题?

android retrofit android-mvvm
1个回答
1
投票

錯誤

你的视图模型中出现的错误是。

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

所以在解析你的回应时出现了问题 您正在接收它,但解析错误。

原因是

在调用这个GET请求(你正在使用的)后。

https://api.github.com/search/users?q=some_name

我收到:

{
  "total_count": 0,
  "incomplete_results": false,
  "items": [

  ]
}

Where is problem

以接收为基础 .json 我明白了,作为根元素的是JSON OBJECT。在你的ViewModel中,你期待的是 List<User> (JSON ARRAY),这不是真的。你接收的对象有3个字段。其中一个字段是你的 List<User>.

修正--说明

你必须创建新的模型类来描述你正在接收的数据。为了解析(从json到Java)所有接收到的数据,它应该包含3个字段。

修正--代码

你的新类的例子。

public class GitHubResponse {
    private long totalCount;
    private boolean incompleteResults;
    private List<User> items;
}

并在ViewModel和ViewModel的所有地方使用这个类。APIEndPoint.java. 要访问数据 - 广告getters到这个类。

一般项目提示

  • 重新格式化代码 (Ctrl + 祭祀 + L)

  • 增加 "启动 "状态(因为启动后应用视图是空的)。

  • 添加空状态(当接收到的数据为空时)

  • 添加加载状态(当你正在加载数据并等待响应时)

  • 增加错误状态(当连接失败或数据解析出现问题时)

© www.soinside.com 2019 - 2024. All rights reserved.