Retrofit2 HTTP获取Json到RecyclerView

问题描述:

我想使用Retrofit2来检索数据为JSON,然后解析它到我的RecyclerView适配器,但无论我做什么,我都无法弄清楚如何让这个东西工作。Retrofit2 HTTP获取Json到RecyclerView

目前,我可以用本地DBFlow数据加载一个RecyclerView,但无法弄清楚如何为我的第二个RecyclerView使用Retrofit2进行HTTP GET的JSON。到目前为止,我有下面的代码,它在日志中加载JSON。但不能解析它到RecyclerView。

MainActivity.java:

onCreate() { 
... 
    mGithubApi = ApiUtils.getApi(); 
    mGithubRecyclerView = (RecyclerView) 
    findViewById(R.id.github_repository_recyclerview); 
    RecyclerView.LayoutManager mGithubLayoutManager = new 
    LinearLayoutManager(getApplicationContext()); 
    mGithubRecyclerView.setLayoutManager(mGithubLayoutManager); 
    mGithubRecyclerView.setHasFixedSize(true); 
... 
    loadGithubUserRepositoryJson(); 
} 

// Load Github repo JSON 
public void loadGithubUserRepositoryJson() { 
    Call<ResponseBody> result = api.getRepos("motivecodex"); 
    result.enqueue(new Callback<ResponseBody>() { 
     @Override 
     public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { 
      try { 
       Log.e(LOG_TAG, response.body().string()); 

       mGithubAdapter = new GithubRepositoriesAdapter((List<GithubRepository>) mGithubRepository); 
       mGithubRecyclerView.setAdapter(mGithubAdapter); 

      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 

     @Override 
     public void onFailure(Call<ResponseBody> call, Throwable t) { 
      Log.e("MainActivity", "error loading from API"); 
     } 
    }); 
} 

GithubRepositoryAdapter.java

public class GithubRepositoriesAdapter extends RecyclerView.Adapter<GithubRepositoriesAdapter.RepositoryViewHolder> { 

    private List<GithubRepository> githubRepositoryList; 

    public class RepositoryViewHolder extends RecyclerView.ViewHolder { 
     public TextView repository, commits, stars, forks; 

     public RepositoryViewHolder(View view) { 
      super(view); 
      repository = (TextView) view.findViewById(R.id.listitem_repository); 
      commits = (TextView) view.findViewById(R.id.listitem_commits); 
      stars = (TextView) view.findViewById(R.id.listitem_stars); 
      forks = (TextView) view.findViewById(R.id.listitem_forked); 
     } 
    } 

    public GithubRepositoriesAdapter(List<GithubRepository> githubRepositoryList) { 
     this.githubRepositoryList = githubRepositoryList; 
    } 

    @Override 
    public RepositoryViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 
     View itemView = LayoutInflater.from(parent.getContext()) 
       .inflate(R.layout.listitem_repository, parent, false); 

     return new RepositoryViewHolder(itemView); 
    } 

    @Override 
    public void onBindViewHolder(RepositoryViewHolder holder, int position) { 
     GithubRepository githubRepository = githubRepositoryList.get(position); 
     holder.repository.setText(githubRepository.getName()); 
     holder.commits.setText(githubRepository.getStargazersCount()); 
     holder.stars.setText(githubRepository.getStargazersCount()); 
     holder.forks.setText(githubRepository.getForks()); 
    } 

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

接口Api.java:

@GET("users/{user}/repos") 
Call<List<GithubRepository>> listRepos(@Path("user") String user); 

模型GithubRepository.java

public class GithubRepository { 

    @SerializedName("id") 
    @Expose 
    private Integer id; 

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

    @SerializedName("full_name") 
    @Expose 
    private String fullName; 

    @SerializedName("stargazers_count") 
    @Expose 
    private Integer stargazersCount; 

    @SerializedName("forks") 
    @Expose 
    private Integer forks; 

    public Integer getId() { 
     return id; 
    } 

    public void setId(Integer id) { 
     this.id = id; 
    } 

    public String getName() { 
     return name; 
    } 

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

    public String getFullName() { 
     return fullName; 
    } 

    public void setFullName(String fullName) { 
     this.fullName = fullName; 
    } 

    public Integer getStargazersCount() { 
     return stargazersCount; 
    } 

    public void setStargazersCount(Integer stargazersCount) { 
     this.stargazersCount = stargazersCount; 
    } 

    public Integer getForks() { 
     return forks; 
    } 

    public void setForks(Integer forks) { 
     this.forks = forks; 
    } 
} 

ApiUtil.java

public static final String BASE_URL = "https://api.github.com/users/"; 
public static Api getApi() { 
    return RetrofitClient.getClient(BASE_URL).create(Api.class); 
} 

RetrofitClient.java

public class RetrofitClient { 
    private static Retrofit retrofit = null; 

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

相反的日志(这大约是我不能看到你的类型):

localRepositoryList.addAll(response.body()); 
adapter.notifyDataSetChanged(); 

PS:我承担你在代码中有这样的东西:

GithubRepositoriesAdapter adapter=new GithubRepositoriesAdapter(localRepositoryList); 
mGithubRecyclerView.setAdapter(adapter); 

另一个选项在日志的地方:

mGithubRecyclerView.setAdapter(new GithubRepositoriesAdapter(response.body())); 

UPDATE:

public void loadGithubUserRepositoryJson() { 
    api.listRepos("motivecodex").enqueue(new Callback<List<GithubRepository>>() { 
    @Override 
    public void onResponse(Call<List<GithubRepository>> call, Response<List<GithubRepository>> response) { 
     try { 
      Log.e(LOG_TAG, response.body().string()); 

      mGithubAdapter = new GithubRepositoriesAdapter(response.body()); 
      mGithubRecyclerView.setAdapter(mGithubAdapter); 

     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

    @Override 
    public void onFailure(Call<List<GithubRepository>> call, Throwable t) { 
     Log.e("MainActivity", "error loading from API"); 
    } 
}); 
} 
+0

你好,对不起,在我的问题的一些代码不匹配。我已更新了一些字段。你能再看一遍吗? ''另一个选项''我得到错误: 'java.lang.NullPointerException:试图在空对象引用 com.motivecodex上调用接口方法'int java.util.List.size()'。 githubusers.adapter.GithubRepositoriesAdapter.getItemCount(GithubRepositoriesAdapter.java:62)'这是在'返回githubRepositoryList.size();' – MOTIVECODEX

+1

mGithubAdapter = new GithubRepositoriesAdapter((List )response.body()); 还要确保你得到的数据列表中的response.body()...和not null – Shmuel

+1

ENQUEUE中的所有ResponseBody都是List 。改变它在4个地方。 – Shmuel