在类似WhatsApp的聊天应用程序中,我还添加了friend req功能,用户可以在其中与Firebase数据库成为好友。现在我的应用程序中的错误是:我不应该向自己发送朋友请求,它必须使按钮不可见,但我不知道该隐藏在哪里。我有点困惑。

控制我的应用程序的流程:
全新的应用安装-登录/注册(StartActivity)-重定向到MainActivty-在这里我设置菜单布局和onOptionsItemSelected(MenuItem项目)-这样就存在“所有用户”选项-从那里我选择任何特定用户(UsersActivity)-从而打开用户个人资料用户的身份(即ProfileActivity)-我将获得“发送好友请求”选项。

但是在所有用户活动中,我也会像其他用户一样显示在列表中,当我在个人资料上单击它时,它会显示与其他用户相同的内容,并且还显示了“发送朋友请求”选项。怎么藏起来

我附加了UsersActivity(包括所有吸引我的用户的位置)和ProfileActivity(特定的用户配置文件将打开的位置,在那里我可以获取send friend req选项)

UsersActivity.java

package com.jimmytrivedi.lapitchat;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ServerValue;
import com.squareup.picasso.Picasso;

import de.hdodenhof.circleimageview.CircleImageView;

public class UsersActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private RecyclerView recyclerView;
    private DatabaseReference databaseReference, UserDatabaseReference;
    private FirebaseAuth mAuth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_users);

        toolbar = findViewById(R.id.usersToolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle("All Users");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        mAuth = FirebaseAuth.getInstance();
        UserDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child(mAuth.getCurrentUser().getUid());

        databaseReference = FirebaseDatabase.getInstance().getReference().child("Users");
        databaseReference.keepSynced(true);

        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(UsersActivity.this));
    }

    @Override
    public void onStart() {
        super.onStart();
        startListening();
        FirebaseUser currentUser = mAuth.getCurrentUser();
        if (currentUser != null) {
            UserDatabaseReference.child("Online").setValue("true");
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        FirebaseUser currentUser = mAuth.getCurrentUser();
        if (currentUser != null) {
            UserDatabaseReference.child("Online").setValue(ServerValue.TIMESTAMP);
        }
    }

    public void startListening() {
        Query query = FirebaseDatabase.getInstance()
                .getReference()
                .child("Users")
                .limitToLast(50);

        FirebaseRecyclerOptions<Users> options =
                new FirebaseRecyclerOptions.Builder<Users>()
                        .setQuery(query, Users.class)
                        .build();

        FirebaseRecyclerAdapter<Users, UsersViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Users, UsersViewHolder>(options) {
            @Override
            protected void onBindViewHolder(@NonNull UsersViewHolder holder, int position, @NonNull Users users) {
                holder.setName(users.getName());
                holder.setStatus(users.getStatus());
                holder.setThumbImage(users.getThumbImage());

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

                holder.mView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(UsersActivity.this, ProfileActivity.class);
                        intent.putExtra("userID", userID);
                        startActivity(intent);
                    }
                });
            }


            @NonNull
            @Override
            public UsersViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                View view = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.users_single_layout, parent, false);

                return new UsersViewHolder(view);
            }
        };

        recyclerView.setAdapter(firebaseRecyclerAdapter);
        firebaseRecyclerAdapter.startListening();
    }


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

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

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

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

        public void setThumbImage(String thumbImage) {
            CircleImageView circleImageView = mView.findViewById(R.id.userImage);
            Picasso.get().load(thumbImage).placeholder(R.drawable.defaultimage)
                    .into(circleImageView);
        }
    }
}


ProfileActivity

package com.jimmytrivedi.lapitchat;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ServerValue;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;

import java.text.DateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class ProfileActivity extends AppCompatActivity {

    private TextView profileDisplayName, currentStatus, totalFriends;
    private ImageView profileDisplayImage;
    private Button sendFriendRequest, declineFriendRequest;
    private DatabaseReference databaseReference, FriendDatabaseReference, FriendDatabase,
            RootDatabaseReference, UserDatabaseReference;
    private ProgressDialog progressDialog;
    private String current_state;
    private FirebaseUser currentUser;
    private FirebaseAuth mAuth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);

        final String userKey = getIntent().getStringExtra("userID");
        databaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child(userKey);
        FriendDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Friend Request");
        FriendDatabase = FirebaseDatabase.getInstance().getReference().child("Friends");
        currentUser = FirebaseAuth.getInstance().getCurrentUser();
        RootDatabaseReference = FirebaseDatabase.getInstance().getReference();

        mAuth = FirebaseAuth.getInstance();
        UserDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child(mAuth.getCurrentUser().getUid());

        profileDisplayName = findViewById(R.id.profileDisplayName);
        currentStatus = findViewById(R.id.currentStatus);
        totalFriends = findViewById(R.id.totalFriends);
        profileDisplayImage = findViewById(R.id.profileDisplayImage);

        sendFriendRequest = findViewById(R.id.sendFriendRequest);

        declineFriendRequest = findViewById(R.id.declineFriendRequest);
        declineFriendRequest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        current_state = "not_friends";

        declineFriendRequest.setVisibility(View.INVISIBLE);
        declineFriendRequest.setEnabled(false);

        progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("Loading user data");
        progressDialog.setMessage("Please wait while we load the user data");
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.show();


        databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                String displayName = dataSnapshot.child("Name").getValue().toString();
                String displayStatus = dataSnapshot.child("Status").getValue().toString();
                String displayImage = dataSnapshot.child("Image").getValue().toString();

                profileDisplayName.setText(displayName);
                currentStatus.setText(displayStatus);
                Picasso.get().load(displayImage).placeholder(R.drawable.defaultimage).into(profileDisplayImage);

                // ------------FRIENDS LIST / REQUEST FEATURE-------------

                FriendDatabaseReference.child(currentUser.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                        if (dataSnapshot.hasChild(userKey)) {
                            String req_type = dataSnapshot.child(userKey).child("Request Type")
                                    .getValue().toString();
                            if (req_type.equals("receive")) {
                                current_state = "req_received";

                                sendFriendRequest.setText("Accept Friend Request");

                                declineFriendRequest.setVisibility(View.VISIBLE);
                                declineFriendRequest.setEnabled(true);
                            } else if (req_type.equals("sent")) {
                                current_state = "req_sent";
                                sendFriendRequest.setText("Cancel Friend Request");
                                declineFriendRequest.setVisibility(View.INVISIBLE);
                                declineFriendRequest.setEnabled(false);
                            }

                            progressDialog.dismiss();

                        } else {
                            FriendDatabase.child(currentUser.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
                                @Override
                                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                                    if (dataSnapshot.hasChild(userKey)) {
                                        current_state = "friends";
                                        sendFriendRequest.setText("Unfriend this person");

                                        declineFriendRequest.setVisibility(View.INVISIBLE);
                                        declineFriendRequest.setEnabled(false);
                                    }
                                    progressDialog.dismiss();
                                }

                                @Override
                                public void onCancelled(@NonNull DatabaseError databaseError) {
                                    progressDialog.dismiss();
                                }
                            });
                        }

                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError databaseError) {

                    }
                });


            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

        sendFriendRequest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendFriendRequest.setEnabled(false);

                // ------------NOT FRIENDS STATE-------------

                if (current_state.equals("not_friends")) {
                    DatabaseReference NewNotificationDatabase = RootDatabaseReference.child("Notifications").child(userKey).push();
                    String newNotificationId = NewNotificationDatabase.getKey();

                    HashMap<String, String> notificationData = new HashMap<>();
                    notificationData.put("from", currentUser.getUid());
                    notificationData.put("type", "request");

                    Map requestMap = new HashMap();
                    requestMap.put("Friend Request/" + currentUser.getUid() + "/" + userKey + "/" + "Request Type", "sent");
                    requestMap.put("Friend Request/" + userKey + "/" + currentUser.getUid() + "/" + "Request Type", "receive");
                    requestMap.put("Notifications/" + userKey + "/" + newNotificationId, notificationData);

                    RootDatabaseReference.updateChildren(requestMap, new DatabaseReference.CompletionListener() {
                        @Override
                        public void onComplete(@Nullable DatabaseError databaseError, @NonNull DatabaseReference databaseReference) {
                            if (databaseError != null) {
                                Toast.makeText(ProfileActivity.this, "There was some error in sending request", Toast.LENGTH_SHORT).show();
                            } else {
                                current_state = "req_sent";
                                sendFriendRequest.setText("Cancel Friend Request");
                            }
                            sendFriendRequest.setEnabled(true);

                        }
                    });

                }

                // ------------CANCEL REQUEST STATE-------------

                if (current_state.equals("req_sent")) {
                    FriendDatabaseReference.child(currentUser.getUid()).child(userKey).removeValue()
                            .addOnSuccessListener(new OnSuccessListener<Void>() {
                                @Override
                                public void onSuccess(Void aVoid) {
                                    FriendDatabaseReference.child(userKey).child(currentUser.getUid())
                                            .removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
                                        @Override
                                        public void onSuccess(Void aVoid) {
                                            sendFriendRequest.setEnabled(true);
                                            current_state = "not_friends";
                                            sendFriendRequest.setText("Send Friend Request");

                                            declineFriendRequest.setVisibility(View.INVISIBLE);
                                            declineFriendRequest.setEnabled(false);
                                        }
                                    });
                                }
                            });
                }


                // ------------REQUEST RECEIVED STATE-------------

                if (current_state.equals("req_received")) {
                    final String currentDate = DateFormat.getDateTimeInstance().format(new Date());

                    Map friendsMap = new HashMap();
                    friendsMap.put("Friends/" + currentUser.getUid() + "/" + userKey + "/date", currentDate);
                    friendsMap.put("Friends/" + userKey + "/" + currentUser.getUid() + "/date", currentDate);


                    friendsMap.put("Friend Request/" + currentUser.getUid() + "/" + userKey, null);
                    friendsMap.put("Friend Request/" + userKey + "/" + currentUser.getUid(), null);


                    RootDatabaseReference.updateChildren(friendsMap, new DatabaseReference.CompletionListener() {
                        @Override
                        public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {


                            if (databaseError == null) {

                                sendFriendRequest.setEnabled(true);
                                current_state = "friends";
                                sendFriendRequest.setText("Unfriend this Person");

                                declineFriendRequest.setVisibility(View.INVISIBLE);
                                declineFriendRequest.setEnabled(false);

                            } else {

                                String error = databaseError.getMessage();

                                Toast.makeText(ProfileActivity.this, error, Toast.LENGTH_SHORT).show();


                            }

                        }
                    });

                }

                // ------------UNFRIEND STATE-------------

                if (current_state.equals("friends")) {
                    Map unfriendMap = new HashMap();
                    unfriendMap.put("Friends/" + currentUser.getUid() + "/" + userKey, null);
                    unfriendMap.put("Friends/" + userKey + "/" + currentUser.getUid(), null);

                    RootDatabaseReference.updateChildren(unfriendMap, new DatabaseReference.CompletionListener() {
                        @Override
                        public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {


                            if (databaseError == null) {
                                current_state = "not_friends";
                                sendFriendRequest.setText("Send Friend Request");

                                declineFriendRequest.setVisibility(View.INVISIBLE);
                                declineFriendRequest.setEnabled(false);

                            } else {

                                String error = databaseError.getMessage();

                                Toast.makeText(ProfileActivity.this, error, Toast.LENGTH_SHORT).show();


                            }

                            sendFriendRequest.setEnabled(true);

                        }
                    });

                }
            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        FirebaseUser currentUser = mAuth.getCurrentUser();
        if (currentUser != null) {
            UserDatabaseReference.child("Online").setValue("true");
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        FirebaseUser currentUser = mAuth.getCurrentUser();
        if (currentUser != null) {
            UserDatabaseReference.child("Online").setValue(ServerValue.TIMESTAMP);
        }
    }
}


请用代码向我解释。感谢您的努力,也感谢您的帮助。感谢Priyanka!

最佳答案

ProfileActivity中,找出您所显示的用户是否为登录用户(将您使用userKeycurrentUser进行比较的用户)。如果是这样,请像这样隐藏sendFriendRequest

sendFriendRequest.setVisibility(View.GONE);


另外,您可以禁用按钮:

sendFriendRequest.setEnabled(false);

关于java - 如何禁用向自身发送好友请求的按钮?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51368237/

10-12 15:23