如何使用ParseQueryAdapter从另一个类获取数据(Android + Parse)

时间:2014-06-29 23:12:40

标签: android android-listview parse-platform

我正在尝试使用ParseQueryAdapter在列表视图中显示用户名和照片。我有课程:UserPost

我在这里设置:

String[] postsObjectIds = some_string_array

ParseQueryAdapter<Post> adapter = new ParseQueryAdapter<Post>(getActivity(), new ParseQueryAdapter.QueryFactory<Post>() {
        public ParseQuery<Post> create() {
            ParseQuery<Post> query = Post.getQuery();
            query.include("User");
            query.whereContainedIn("objectId", Arrays.asList(postsObjectIds));
            return query;
        }
});

adapter.setTextKey("username");
adapter.setImageKey("photo");
adapter.setPlaceholder(getResources().getDrawable(R.drawable.some_drawable));

ListView listView = (ListView) rootView.findViewById(R.id.post_list_view);
listView.setAdapter(adapter);

Post类有一个名为photo的列,User类有一个名为username的列。列表视图未显示用户名。

我是否必须实施自定义适配器? 有快速解决方法吗?

1 个答案:

答案 0 :(得分:3)

我在Parse帮助论坛上找到了答案:

ParseQueryAdapter setTextKey for relational object

接受的答案是使用自定义ParseQueryAdapter<T>Override getItemView

例如,在我的Fragment的onCreateView方法中,我初始化了适配器并对其进行了设置(postsObjectIdsString[]}:

PostViewListViewAdapter adapter = new PostViewListViewAdapter(getActivity(), postsObjectIds);

ListView listView = (ListView) rootView.findViewById(R.id.post_list_view);
listView.setAdapter(adapter);

这是我的适配器(PostViewListViewAdapter):

public class PostViewListViewAdapter extends ParseQueryAdapter<Post> {

    private final String[] mPostsObjectIds;

    public PostViewListViewAdapter(Context context, final String[] postsObjectIds) {
        super(context, new ParseQueryAdapter.QueryFactory<Post>(){
            public ParseQuery<Post> create() {
                ParseQuery<Post> query = Post.getQuery();
                query.include("User");

                query.whereContainedIn("objectId", Arrays.asList(postsObjectIds));
                return query;
            }
        });
        this.mPostsObjectIds = postsObjectIds;
    }

    @Override
    public View getItemView(Post post, View v, ViewGroup parent) {
        if(v == null) {
            v = View.inflate(getContext(), R.layout.list_item_post_view, null);
        }

        super.getItemView(post, v, parent);

        final TextView usernameTextView = (TextView) v.findViewById(R.id.username_text_view);

        post.getCreator().fetchIfNeededInBackground(new GetCallback<ParseUser>() {
            @Override
            public void done(ParseUser user, ParseException e) {
                usernameTextView.setText(user.getUsername());
            }
        });
        return v;
    }
}