【问题标题】:cannot put values inside Array List不能将值放入数组列表中
【发布时间】:2020-01-21 14:20:10
【问题描述】:

我尝试在 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);
        }
    }

【问题讨论】:

  • 我猜你的基本网址是错误的
  • 你的 json 中的data 在哪里????
  • 这是数组包含数据列表 mBlogWrapper 但我无法将数据放入电影数组中
  • 您所做的是映射 List,但该 json 不提供 data

标签: java android android-livedata android-json


【解决方案1】:

试试这个代码,对不起,我不在笔记本电脑上……也许你可以从中理解。我只是将响应对象切换为List&lt;Blog2&gt;,因为你需要它

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

现在您有了 List 中的值,然后您可以将其值存储到 MutableLivedata。

别忘了改变你的改造方法

public interface RestApiService {

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

}

【讨论】:

  • 谢谢,但我想练习存储库,我必须在参数里面添加。新回调>
  • 只有在得到响应结果后才能创建Blog2对象。为什么?因为您的 json 数据没有为 Blogwrapper 提供序列化。如果您想从响应中获取List&lt;BlogWrapper&gt;,请更改您的 API json
  • 好的,我将为 Blog2 实现序列化,你能看到我使用 参数的 Repository 的一些代码
  • 如果你想处理错误响应,那么在每个方法(onResponse,onFailure)中创建BlogWrapper对象然后设置它为blog2数据,所以如果它出现onFailure那么你可以设置BlogWrapper错误回复。对于这种情况,您不需要 List 。那么你的 MutableLivedata 类型应该是BlogWrapper
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-23
  • 2020-06-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多