android - 无法使用 JSON 数据填充布局

标签 android json android-layout android-fragments retrofit

我正在尝试通过遍历一些请求的 JSON 来填充我的布局(我使用 Retrofit )。

当我尝试手动填充布局时(如下所示),它显示正常:

Post post1 = new Post("1", "1", "This is a message.");

但是如果我尝试用请求的 JSON 数据填充它,布局不会被填充也不会显示在我的屏幕上。只有带有“这是一条消息”的布局。显示。

这是我的 fragment 的 onCreateView() 中的代码:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_main, container, false);
    ListView listView = (ListView) view.findViewById(R.id.listview_posts);

    final ArrayList<Post> arrayOfUsers = new ArrayList<Post>();

    // This works fine. It populates the layout as it should.
    Post post1 = new Post("1", "1", "This is a message.");
    arrayOfUsers.add(post1);

    final RestAdapter restAdapter = new RestAdapter.Builder()
            .setEndpoint(BASE_URL)
            .build();

    final ApiEndpointInterface apiService = restAdapter.create(ApiEndpointInterface.class);

    apiService.getJsonStuff(1, new Callback<PostData>() {

        @Override
        public void success(PostData postData, Response response) {

            // This doesn't work either
            Post post2 = new Post("1", "1", "This is a message2.");
            arrayOfUsers.add(post2);

            for (Post p : postData.data) {

                // This does not work. The layout isn't populated nor does it display.
                Post posty = new Post(p.getId(), p.getUserId(), p.getContent());
                arrayOfUsers.add(posty);

                // The JSON is being read correctly, since this prints out the right values.
                Log.d("MESSAGE", p.getMessage());
            }
        }

        @Override
        public void failure(RetrofitError retrofitError) {
            retrofitError.printStackTrace();
        }
    });

    PostAdapter adapter = new PostAdapter(getActivity(), arrayOfUsers);
    listView.setAdapter(adapter);

    return view;
}

回调:

void getJsonStuff(@Path("user_id") int userId, Callback<PostData> response);

发布模型:

import java.util.ArrayList;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Post {

    @Expose
    private String id;
    @SerializedName("user_id")
    @Expose
    private String userId;
    @Expose
    private String content;

    public Post(String id, String userId, String content) {
        this.id = id;
        this.userId = userId;
        this.content = content;
    }

    /**
     *
     * @return
     * The id
     */
    public String getId() {
        return id;
    }

    /**
     *
     * @param id
     * The id
     */
    public void setId(String id) {
        this.id = id;
    }

    /**
     *
     * @return
     * The userId
     */
    public String getUserId() {
        return userId;
    }

    /**
     *
     * @param userId
     * The user_id
     */
    public void setUserId(String userId) {
        this.userId = userId;
    }

    /**
     *
     * @return
     * The content
     */
    public String getContent() {
        return content;
    }

    /**
     *
     * @param content
     * The content
     */
    public void setContent(String content) {
        this.content= content;
    }

}

PostData 模型:

import java.util.ArrayList;
import java.util.List;
import com.google.gson.annotations.Expose;

public class PostData {

    @Expose
    public Boolean success;
    @Expose
    public List<Post> data = new ArrayList<Post>();

    /**
     *
     * @return
     * The success
     */
    public Boolean getSuccess() {
        return success;
    }

    /**
     *
     * @param success
     * The success
     */
    public void setSuccess(Boolean success) {
        this.success = success;
    }

    /**
     *
     * @return
     * The data
     */
    public List<Post> getData() {
        return data;
    }

    /**
     *
     * @param data
     * The data
     */
    public void setData(List<Post> data) {
        this.data = data;
    }

}

最佳答案

在适合您的场景中 -> 您按顺序执行操作:创建 Post 对象 - 将其添加到列表 - 基于非空列表创建适配器 - 在列表中设置适配器。

在不起作用的情况下,您正在异步执行它们:创建空列表 - 触发数据请求(但还没有数据) - 创建适配器 - 在列表中设置适配器 - 在未来某个不确定的时刻数据到达。问题是,在这种情况下,适配器不知道有任何更改,因此您需要通知它(在 success 回调结束时): adapter.notifyDataSetChanged()

关于android - 无法使用 JSON 数据填充布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32085459/

相关文章:

android - 延迟后方法 - Android

javascript - 如何使用 JavaScript 搜索 JSON 树

c# - 在 JSON.NET 中如何获取对每个反序列化对象的引用?

java - <String, String> HashMap 中的整数对象

android - TableLayout 中的 TextView 仅在配置更改后居中

android - 切换 fragment 时跳转滚动

java - 如何将多个视频文件一起写入以创建一个视频文件

android - ServerSocket 的服务 - 它应该在一个单独的线程中吗?

android - 对 GCM token 更新过程感到困惑

java - 从 Activity 中打开 fragment 并膨胀 View