Firebase同步方法不同步

时间:2018-10-24 12:54:59

标签: android firebase firebase-realtime-database firebaseui

代码

public class HomeScreen_Friends extends Fragment {

    private View rootView;
    private String userName;
    private String UID;
    private TextView noUsersText;
    private ProgressDialog mProgressDialogue;

    private FirebaseAuth mAuth;
    private FirebaseUser currentUser;
    private  DatabaseReference mDatabaseReference;
    private  DatabaseReference mUsersDatabase;

    private RecyclerView mUsersList;
    private FirebaseRecyclerAdapter<AllUsersHelper, UsersViewHolder> firebaseRecyclerAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_friends, container, false);

        noUsersText = (TextView) rootView.findViewById(R.id.noUsersText);
        mUsersList = (RecyclerView) rootView.findViewById(R.id.usersList);
        mUsersList.addItemDecoration(new DividerItemDecoration(getContext(),
                DividerItemDecoration.HORIZONTAL));


        mAuth = FirebaseAuth.getInstance();
        currentUser = mAuth.getCurrentUser();
        UID = mAuth.getCurrentUser().getUid();
        mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Friends").child(UID);
        mDatabaseReference.keepSynced(true);
        mUsersDatabase = FirebaseDatabase.getInstance().getReference().child("UserData");
        mUsersDatabase.keepSynced(true);

        mProgressDialogue = new ProgressDialog(getActivity());
        mProgressDialogue.setMessage("Loading...");
        mProgressDialogue.show();

        mUsersList.setLayoutManager(new LinearLayoutManager(getActivity()));

        FirebaseRecyclerOptions<AllUsersHelper> options =
                new FirebaseRecyclerOptions.Builder<AllUsersHelper>()
                        .setQuery(mDatabaseReference, AllUsersHelper.class)
                        .build();

        firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<AllUsersHelper, UsersViewHolder>(options) {

            @Override
            protected void onBindViewHolder(@NonNull final UsersViewHolder holder, int position, @NonNull AllUsersHelper model) {
                holder.setName(model.getName());
                holder.setStatus(model.getStatus());
                holder.setImage(model.getImage());

                final String userId = getRef(position).getKey();

                mUsersDatabase.orderByChild("Name");
                mUsersDatabase.child(userId).addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {

                        String mName = dataSnapshot.child("Name").getValue().toString();
                        String mStatus = dataSnapshot.child("Status").getValue().toString();
                        String mDisplayImage = dataSnapshot.child("Image").getValue().toString();

                        if(dataSnapshot.hasChild("Online")) {

                            String userOnline = dataSnapshot.child("Online").getValue().toString();
                            holder.setUserOnline(userOnline);

                        }
                        holder.setName(mName);
                        holder.setImage(mDisplayImage);
                        holder.setStatus(mStatus);
                        mProgressDialogue.dismiss();

                    }
                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });



                holder.mView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("UserData").child(userId);

                        rootRef.addListenerForSingleValueEvent(new ValueEventListener() {
                            @Override
                            public void onDataChange(DataSnapshot dataSnapshot) {
                                userName = dataSnapshot.child("Name").getValue().toString();
                                Intent intent = new Intent(getActivity(), Chat.class);
                                intent.putExtra("Recievers_Id", userId);
                                intent.putExtra("Recievers_Name", userName);
                                startActivity(intent);
                            }
                            @Override
                            public void onCancelled(DatabaseError databaseError) {
                            }
                        });
                    }
                });
            }




                    @Override
            public UsersViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                View view = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.custom_activity_all_users, parent, false);
                return new UsersViewHolder(view);
            }
        };
        mUsersList.setAdapter(firebaseRecyclerAdapter);
        return rootView;
    }

    public static class UsersViewHolder extends RecyclerView.ViewHolder {
    public View mView;

    public UsersViewHolder(View itemView) {
        super(itemView);
        mView = itemView;
    }

    public void setName(String name) {
        TextView mDisplayName = (TextView) mView.findViewById(R.id.display_name);
        mDisplayName.setText(name);
    }

    public void setStatus(String status) {
        TextView mDisplayStatus = (TextView) mView.findViewById(R.id.display_status);
        mDisplayStatus.setText(status);
    }

    public void setImage(String image) {
        CircularImageView mDisplayImage = (CircularImageView) mView.findViewById(R.id.circleImageView);
        Picasso.get().load(image).into(mDisplayImage);
    }

    public void setUserOnline(String userOnline) {
        ImageView userOnlineView = (ImageView) mView.findViewById(R.id.online);

        if(userOnline.equals("Online")){

            userOnlineView.setVisibility(View.VISIBLE);

        } else {

            userOnlineView.setVisibility(View.INVISIBLE);

        }

    }
    }

    @Override
    public void onStart() {
        super.onStart();
        firebaseRecyclerAdapter.startListening();
    }
    @Override
    public void onStop() {
        super.onStop();
        if(firebaseRecyclerAdapter != null) {
            firebaseRecyclerAdapter.stopListening();
        }
    }

}

我应该在哪里将keepSynced方法离线获取数据,因为我尝试在数据库引用下面进行操作,并且当我没有互联网时它仍然无法显示我的数据。有人可以帮帮我吗...另外,如果resukt为null,我如何停止进度对话框并显示一条文本,指出没有用户。

1 个答案:

答案 0 :(得分:1)

现在,您只是告诉Firebase在FriendsUserData节点上保持一个空的侦听器处于活动状态。这样可以确保这些节点中的数据始终保持最新(即使您不附加任何其他侦听器),但数据仍仅保留在内存中。

要将内存缓存持久化到磁盘上,以便在启动应用程序时没有互联网连接时可以重新加载它,您需要在应用程序启动时调用FirebaseDatabase.getInstance().setPersistenceEnabled(true)。请参阅Firebase文档中的enabling disk persistence

另请参阅: