使用Firebase填充我的ListView

时间:2016-09-22 23:17:55

标签: android listview firebase firebase-realtime-database

我正在使用Firebase作为我的应用程序的数据库。当我想用Firebase填充ListView时,我遇到了问题。

以下是我正在使用的结果,代码和数据库的图片。所以我问自己,问题是代码问题还是构建数据库的问题。谢谢。

结果 - 结果实际应该是:单词Test应该在链接所在的位置,而是将其添加为新元素:

Firebase数据库:

这是我用来填充ListView的方法:

private void populateUserInfoList() {
    firebase = new Firebase("https://top-ten-317ef.firebaseio.com");
    firebase.child("ToptenListItem").addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {

            for (DataSnapshot child : snapshot.getChildren()) {
                String TopTitle = (String) child.getValue(Boolean.parseBoolean("toptitle"));
                String TopPosterPic = (String) child.getValue(Boolean.parseBoolean("topposter"));
                ToptenListItem info = new ToptenListItem(TopTitle, TopPosterPic);
                TopArrayList.add(info);

            }
            Collections.addAll(TopArrayList);
            ToptenItemAdapter adapteri = new ToptenItemAdapter(getContext(), R.layout.itemrow, TopArrayList);
            itemListView.setAdapter(adapteri);

        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {
            String message = "Server error. Refresh page";
            Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
        }


    });
}

1 个答案:

答案 0 :(得分:0)

我建议您使用RecyclerView而不是列表,Android创建了RecyclerView作为ListView改进,所以是的,您可以使用ListView控件创建附加列表,但使用RecyclerView更容易,更好。您可以在这篇文章中阅读更多内容:RecyclerView vs ListView

此外,您可以使用FirebaseRecyclerAdapter恢复列表的适配器,它将为您填充列表并检索所需的所有数据(我通常在我的代码中使用自定义对象)完成所有工作它等于我的firebase数据库的值,这样就可以在FirebaseRecyclerAdapter中使用它们来改进数据检索)

例如,我在这里使用FirebaseRecyclerAdapter填充带有个人资料图片的用户的列表视图:

 private void initializeRecyclerAdapter() {
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
    linearLayoutManager.setReverseLayout(true);
    linearLayoutManager.setStackFromEnd(true);
    mRecyclerUsersView.setLayoutManager(linearLayoutManager);

    Query allPostsQuery = FirebaseUtil.getUsersRef();
    mAdapter = getFirebaseRecyclerAdapter(allPostsQuery);
    mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
        @Override
        public void onItemRangeInserted(int positionStart, int itemCount) {
            super.onItemRangeInserted(positionStart, itemCount);
            // TODO: Refresh feed view.
        }
    });

    mRecyclerUsersView.setAdapter(mAdapter);
}

private FirebaseRecyclerAdapter<User, UserListViewHolder> getFirebaseRecyclerAdapter(Query query) {
    return new FirebaseRecyclerAdapter<User, UserListViewHolder>(
            User.class, R.layout.user_row_item, UserListViewHolder.class, query) {

        @Override
        protected void populateViewHolder(UserListViewHolder viewHolder, User user, int position) {
            setupUser(viewHolder, user, position, null);
        }

    };
}

private void setupUser(final UserListViewHolder UserViewHolder, final User user, final int position, final String inPostKey) {
    //Set the items for every new view
    UserViewHolder.setIcon(user.getPhoto_url());
    UserViewHolder.setText(user.getEmail());
    final String postKey;
    if (mAdapter instanceof FirebaseRecyclerAdapter) {
        postKey = ((FirebaseRecyclerAdapter) mAdapter).getRef(position).getKey();
    } else {
        postKey = inPostKey;
    }
    FirebaseUtil.getUsersRef().child(postKey).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(final DataSnapshot dataSnapshot) {
            //Add users to the newGroup item
            UserViewHolder.setPostClickListener(new UserListViewHolder.UserClickListener() {
                @Override
                public void onUserClick() {
                   // mNewGroup.addUserToGroup(dataSnapshot.getKey());
                    mNewGroupUsers.addUserToGroup(dataSnapshot.getKey());
                }
            });
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            //TODO ControlOnCancelled
        }
    });
}

而且,正如您所看到的,我的User对象非常简单(对象变量的名称必须等于您的firebase项目,对于子级别,您可以在对象中使用Hashmaps):

public class User {
private String display_name;
private String email;
private String photo_url;


  //[...] get/set methods and constructors

最后,这是我的viewHolder用户类:

public class UserListViewHolder extends RecyclerView.ViewHolder {
    private final View mView;
    private static final int POST_TEXT_MAX_LINES = 6;
    private ImageView mIconView;
    private TextView mAuthorView;
    private UserClickListener mListener;

    public UserListViewHolder(View itemView) {
        super(itemView);
        mView = itemView;
        mIconView = (ImageView) mView.findViewById(R.id.user_image_profile);
        mAuthorView = (TextView) mView.findViewById(R.id.user_text_profile);
        mView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mListener.onUserClick();
            }
        });
    }

    public void setIcon(String url) {
        GlideUtil.loadProfileIcon(url, mIconView);
    }

    public void setPostClickListener(UserClickListener listener) {
        mListener = listener;
    }


    public void setText(final String text) {
        if (text == null || text.isEmpty()) {
            mAuthorView.setVisibility(View.GONE);
            return;
        } else {
            mAuthorView.setVisibility(View.VISIBLE);
            mAuthorView.setText(text);
            mAuthorView.setMaxLines(POST_TEXT_MAX_LINES);
        }
    }

    public interface UserClickListener {
        void onUserClick();
    }
}

随意提出任何疑问!希望它能帮到你!