java - Retrofit2 HTTP 获取 Json 到 RecyclerView

标签 java android json retrofit2

我正在尝试使用 Retrofit2 以 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();
    }
}

接口(interface)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();

P.S:我假设您的代码中有类似以下内容的内容:

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

日志位置的另一个选项:

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

更新:

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");
    }
});
}

关于java - Retrofit2 HTTP 获取 Json 到 RecyclerView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46635221/

相关文章:

java - 单例比静态好?

java - 依赖更新后gradle构建失败

android - avcodec_encode_video2() 错误 -1 : Could not encode video packet - javacv

ruby-on-rails - 解析从 Unity 发送到 Ruby On Rails 的 JSON POST 数据

python - 如何使用 json.dumps() 将嵌套字典中的所有 int 转换为 str?

Javascript 和 Node.js - 发出 JSON 请求

Java 8 lambda 嵌套 Map

java - 开发自定义的Talend组件:如何创建不需要输入或输出的真正自定义的东西?

android - 在哪里可以找到有关 Android Studio 中过时 API 的调试信息?

android - 在低端设备上读取大型 XML 时,getXml() 内存不足