0

I am building an App that will add emergency contacts but it has to be strictly 10 people who can be an emergency contact per each user and if it exceeds that it must tell the user that his/her emergency contacts are fully, problem is i don't know how to set the allowed values to be

public class EmergencyList extends AppCompatActivity {

private Toolbar mToolbar;

private TextView mProfileName, mProfileStatus, mProfileFriendsCount;
private Button mProfileSendReqBtn, mDeclineBtn;

private DatabaseReference mUsersDatabase;

private ProgressDialog mProgressDialog;

private DatabaseReference mFriendReqDatabase;
private DatabaseReference mFriendDatabase;
private DatabaseReference mNotificationDatabase;
private ImageView mProfileImage;


private DatabaseReference mRootRef;

private FirebaseUser mCurrent_user;

private String mCurrent_state;



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

    mToolbar = (Toolbar)findViewById(R.id.user_Appbar);
    setSupportActionBar(mToolbar);
    getSupportActionBar().setTitle("Who to notify in emergency");
    mToolbar.setTitleTextColor(android.graphics.Color.WHITE);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    final String user_id = getIntent().getStringExtra("user_id");


    mRootRef = FirebaseDatabase.getInstance().getReference();

    mUsersDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(user_id);
    mFriendReqDatabase = FirebaseDatabase.getInstance().getReference().child("Connection_req");
    mFriendDatabase = FirebaseDatabase.getInstance().getReference().child("Emergency_Contacts");
    mNotificationDatabase = FirebaseDatabase.getInstance().getReference().child("Emergency_Notification");
    mCurrent_user = FirebaseAuth.getInstance().getCurrentUser();




    mProfileImage = (ImageView) findViewById(R.id.profile_image);
    mProfileName = (TextView) findViewById(R.id.profile_displayName);
    mProfileStatus = (TextView) findViewById(R.id.profile_status);
    mProfileFriendsCount = (TextView) findViewById(R.id.profile_totalFriends);
    mProfileSendReqBtn = (Button) findViewById(R.id.profile_send_req_btn);
    mDeclineBtn = (Button) findViewById(R.id.profile_decline_btn);


    mCurrent_state = "not_emergency_contact";

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


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



    mUsersDatabase.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            String display_name = dataSnapshot.child("name").getValue().toString();
            String status = dataSnapshot.child("status").getValue().toString();
            String image = dataSnapshot.child("profile_picture").getValue().toString();

            mProfileName.setText(display_name);
            mProfileStatus.setText(status);

            Picasso.with(EmergencyList.this).load(image).placeholder(R.drawable.my_profile).into(mProfileImage);

            if(mCurrent_user.getUid().equals(user_id)){

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

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

            }


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

            mFriendReqDatabase.child(mCurrent_user.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {

                    if(dataSnapshot.hasChild(user_id)){

                        String req_type = dataSnapshot.child(user_id).child("emergency_type").getValue().toString();

                        if(req_type.equals("received")){

                            mCurrent_state = "emergency_received";
                            mProfileSendReqBtn.setText("Accept As Emergency ");

                            mDeclineBtn.setVisibility(View.VISIBLE);
                            mDeclineBtn.setEnabled(true);


                        } else if(req_type.equals("sent")) {

                            mCurrent_state = "emergency_sent";
                            mProfileSendReqBtn.setText("Cancel Emergency Request");

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

                        }

                        mProgressDialog.dismiss();


                    } else {


                        mFriendDatabase.child(mCurrent_user.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
                            @Override
                            public void onDataChange(DataSnapshot dataSnapshot) {

                                if(dataSnapshot.hasChild(user_id)){

                                    mCurrent_state = "emergency_contact";
                                    mProfileSendReqBtn.setText("Remove "+mProfileName.getText() + " As Emergency Contact");

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

                                }

                                mProgressDialog.dismiss();

                            }

                            @Override
                            public void onCancelled(DatabaseError databaseError) {

                                mProgressDialog.dismiss();

                            }
                        });

                    }



                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });


        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });


    mProfileSendReqBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            mProfileSendReqBtn.setEnabled(false);

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

            if(mCurrent_state.equals("not_emergency_contact")){


                DatabaseReference newNotificationref = mRootRef.child("Emergency_Notification").child(user_id).push();
                String newNotificationId = newNotificationref.getKey();

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

                Map requestMap = new HashMap();
                requestMap.put("Connection_req/" + mCurrent_user.getUid() + "/" + user_id + "/emergency_type", "sent");
                requestMap.put("Connection_req/" + user_id + "/" + mCurrent_user.getUid() + "/emergency_type", "received");
                requestMap.put("Emergency_Notifications/" + user_id + "/" + newNotificationId, notificationData);

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

                        if(databaseError != null){

                            Toast.makeText(EmergencyList.this, "There was some error in sending request", Toast.LENGTH_SHORT).show();

                        } else {

                            mCurrent_state = "emergency_sent";
                            mProfileSendReqBtn.setText("Cancel Emergency Contact");

                        }

                        mProfileSendReqBtn.setEnabled(true);


                    }
                });

            }


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

            if(mCurrent_state.equals("emergency_sent")){

                mFriendReqDatabase.child(mCurrent_user.getUid()).child(user_id).removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {

                        mFriendReqDatabase.child(user_id).child(mCurrent_user.getUid()).removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
                            @Override
                            public void onSuccess(Void aVoid) {


                                mProfileSendReqBtn.setEnabled(true);
                                mCurrent_state = "not_emergency_contact";
                                mProfileSendReqBtn.setText("Add As Emergency Contact");

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


                            }
                        });

                    }
                });

            }


            // ------------ REQ RECEIVED STATE ----------

            if(mCurrent_state.equals("emergency_received")){

                final String currentDate = DateFormat.getDateTimeInstance().format(new Date());

                Map friendsMap = new HashMap();
                friendsMap.put("Emergency_Contact/" + mCurrent_user.getUid() + "/" + user_id + "/date", currentDate);
                friendsMap.put("Emergency_Contact/" + user_id + "/"  + mCurrent_user.getUid() + "/date", currentDate);


                friendsMap.put("Connection_req/" + mCurrent_user.getUid() + "/" + user_id, null);
                friendsMap.put("Connection_req/" + user_id + "/" + mCurrent_user.getUid(), null);


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


                        if(databaseError == null){

                            mProfileSendReqBtn.setEnabled(true);
                            mCurrent_state = "emergency_contact";
                            mProfileSendReqBtn.setText("Remove " + mProfileName.getText() + " As Emergency Contact");

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

                        } else {

                            String error = databaseError.getMessage();

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


                        }

                    }
                });

            }


            // ------------ UNFRIENDS ---------

            if(mCurrent_state.equals("emergency_contact")){

                Map unfriendMap = new HashMap();
                unfriendMap.put("Emergency_Contact/" + mCurrent_user.getUid() + "/" + user_id, null);
                unfriendMap.put("Emergency_Contact/" + user_id + "/" + mCurrent_user.getUid(), null);

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


                        if(databaseError == null){

                            mCurrent_state = "not_emergency_contact";
                            mProfileSendReqBtn.setText("Add As Emergency Contact");

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

                        } else {

                            String error = databaseError.getMessage();

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


                        }

                        mProfileSendReqBtn.setEnabled(true);

                    }
                });

            }


        }
    });


}


}

Any advice on how to add only a finite number of people as the emergency contacts and when it exceeds that number to return a message saying the emergency contacts are full?

1 Answers1

0

To solve this there are actually three ways.

One way would be client side and for that I recomend you attach a listener on the node on which you want store the maximum number of 10 contacts and use a getChildrenCount() method on the DataSnapshot object. Then just use an if statement:

if(dataSnapshot.getChildrenCount() <= 10) {
    //Add contact
} else {
    Log.d("TAG", "The maximum number of contacts has been reached!");
}

The second way would be to limit number of records that can be written to a specific path using Firebase Security Rules. There are a few posts on SOF regarding this approach and for that I recomend you see Kato' answer from this post.

The third way would be to write a function in Firebase Could Function that will help you remove the first or 11'th contact once it was written to a specific path.

So according to your needs, you can choose which one of this three solution is best for your application.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • thanks Alex the first one looks fine i'll have a look at it but i will let you know if i encounter any problems – Malusi Gcabashe Feb 03 '18 at 07:35
  • Ok, perfect. Keep me posted. – Alex Mamo Feb 03 '18 at 07:36
  • should i use the for statement to get the children count or it's an inbuilt function from android (dataSnapShot.getChildrenCount())? – Malusi Gcabashe Feb 03 '18 at 07:39
  • See [DataSnapshot](https://firebase.google.com/docs/reference/android/com/google/firebase/database/DataSnapshot) class documentation. `getChildrenCount()` is method within this class which return a `long`. – Alex Mamo Feb 03 '18 at 08:22