java - 无法将值放入数组列表中

标签 java android android-livedata android-json

我尝试在 BlogRepository 类的 movies ArrayList 内设置值。 但最终没找到结果。

我想修改示例,使 ArrayList 内的存储为电影。 所以这个例子是有效的,结果表明这个例子是有效的。

json 数据:

[
      {
        "albumId": 1,
        "id": 1,
        "title": "accusamus beatae ad facilis cum similique qui sunt",
        "url": "https://via.placeholder.com/600/92c952",
        "thumbnailUrl": "https://via.placeholder.com/150/92c952"
      },
      {
        "albumId": 1,
        "id": 2,
        "title": "reprehenderit est deserunt velit ipsam",
        "url": "https://via.placeholder.com/600/771796",
        "thumbnailUrl": "https://via.placeholder.com/150/771796"
      },
      {
        "albumId": 1,
        "id": 3,
        "title": "officia porro iure quia iusto qui ipsa ut modi",
        "url": "https://via.placeholder.com/600/24f355",
        "thumbnailUrl": "https://via.placeholder.com/150/24f355"
      }
]

代码:

    // 
    public class BlogRepository {

        private ArrayList<Blog2> movies = new ArrayList<>();

        private MutableLiveData<List<Blog2>> mutableLiveData = new MutableLiveData<>();

        private Application application;

        public BlogRepository(Application application){

            this.application = application;
        }

        public MutableLiveData<List<Blog2>> getMutableLiveData() {
            RestApiService service = RetrofitInstance.getApiService();
            Call<List<BlogWrapper>> call = service.getPopularBlog();
            call.enqueue(new Callback<List<BlogWrapper>>(){
                @Override
                public void onResponse(Call<List<BlogWrapper>> call, Response<List<BlogWrapper>> response) {
                    List<BlogWrapper> mBlogWrapper = response.body();
                    for (int i=0; i<mBlogWrapper.size(); i++) {
                       movies = (ArrayList<Blog2>) mBlogWrapper.get(i).getBlog();
                        //Log.d("trace_movies : ",""+ movies);
                    }
                }
                @Override
                public void onFailure(Call<List<BlogWrapper>> call, Throwable t) {
                  //  Toast.makeText(MainActivity.this, "Unable to load users", Toast.LENGTH_SHORT).show();
                    Log.e("trace_2",""+t.getMessage().toString());
                }
            });
            return mutableLiveData;
        }

    }

    // 

    public class Blog2 {

        @SerializedName("albumId")
        private int albumId;
        @SerializedName("id")
        private int id;
        @SerializedName("title")
        private String title;
        @SerializedName("url")
        private String url;
        @SerializedName("thumbnailUrl")
        private String thumbnailUrl;


        public void setAlbumId(int albumId) {
            this.albumId = albumId;
        }

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

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

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

        public void setThumbnailUrl(String thumbnailUrl) {
            this.thumbnailUrl = thumbnailUrl;
        }


        public int getAlbumId() {
            return albumId;
        }

        public int getId() {
            return id;
        }

        public String getTitle() {
            return title;
        }

        public String getUrl() {
            return url;
        }

        public String getThumbnailUrl() {
            return thumbnailUrl;
        }
    }

    /// 

    public class BlogWrapper {

        @SerializedName("data")
        private List<Blog2> mData;
        @SerializedName("error")
        private Boolean mError;
        @SerializedName("message")
        private String mMessage;
        @SerializedName("status")
        private String mStatus;

        public List<Blog2>getBlog() {
            return mData;
        }

        public void setBlog(List<Blog2> data) {
            mData = data;
        }

        public Boolean getError() {
            return mError;
        }

        public void setError(Boolean error) {
            mError = error;
        }

        public String getMessage() {
            return mMessage;
        }

        public void setMessage(String message) {
            mMessage = message;
        }

        public String getStatus() {
            return mStatus;
        }

        public void setStatus(String status) {
            mStatus = status;
        }

    }

    /// 

    public interface RestApiService {

      @GET("/photos")
      public Call<List<BlogWrapper>> getPopularBlog();

    }

    // 

    public class RetrofitInstance {

        private static Retrofit retrofit = null;
        public static final String BASE_URL_ = "https://jsonplaceholder.typicode.com/albums/1/";
         // public static final String BASE_URL_ = "https://androidwave.com/api/";
         public static RestApiService getApiService() {
             Gson gson = new GsonBuilder().setLenient().create();
            if (retrofit == null) {
                retrofit = new retrofit2.Retrofit
                 .Builder()
                   .baseUrl(BASE_URL_)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                      .build();

            }
            return retrofit.create(RestApiService.class);
        }
    }

最佳答案

试试这个代码,抱歉我不在笔记本电脑旁......也许你可以从中理解。我只是将响应对象切换为 List<Blog2> ,因为你需要它

call.enqueue(new Callback<List<Blog2>>(){
                @Override
                public void onResponse(Call<List<Blog2>> call, Response<List<Blog2>> response) {
                    List<Blog2> mBlogWrapper = response.body();
                    for (int i=0; i<mBlogWrapper.size(); i++) {
                       movies.add(mBlogWrapper.get(i));
                        //Log.d("trace_movies : ",""+ movies);
                    }
                }
            });

现在您已经从列表中获得了值,然后您可以将其值存储到 MutableLivedata。

另外不要忘记更改您的 Retrofit 方法

public interface RestApiService {

  @GET("/photos")
  public Call<List<Blog2>> getPopularBlog();

}

关于java - 无法将值放入数组列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59843120/

相关文章:

Java自定义Exception错误未报告异常

android - Kotlin Retrofit response.body() 返回 null

java - 用于复制 url-webview 的按钮

android - 使用 Room 实时查询进行生命周期状态管理

java - 单击 imageView 时如何显示项目

java - 如何打破方法中的循环

android - 如何使用 DexGuard 混淆 XML 资源文件?

java - 从 ViewModel MutableLiveData 获取值并将其显示在文本字段上

android - LifecycleRegistryOwner 类已弃用

java - Mockito 模拟父类(super class)调用