【发布时间】:2020-05-08 19:56:03
【问题描述】:
我正在试验GitHub search users API。我的目标是编写一个简单的应用程序:输入用户名,任何与之相关的 GitHub 用户名都将显示在 RecyclerView 上(使用 MVVM 模式)。
例如,搜索用户名clive的方法如下:
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);
}
User.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.com/anta40/GithubUserSearch
当我在 SearchView 上键入任何用户名并按 ENTER 键时,不会显示任何搜索结果(recyclerview 仍为空)。经过进一步检查,我发现logcat上显示“DBG:Failed”,这意味着GitHub API没有正确调用。如何解决这个问题?
【问题讨论】:
标签: android retrofit android-mvvm