1

What I want to do is search through client's address book(phone numbers) and only display contacts who are registered on firebase by looking if their phone numbers are registered.(kind of like Whatsapp)

Currently I am displaying all the registered users on firebase

Code:

public class Tab1 extends Fragment {
    private static final String TAG = "MyActivity";
    private Button signOut;
    private FirebaseAuth.AuthStateListener authListener;
    private FirebaseAuth auth;
     ListView listView;
    private DatabaseReference mDatabase;
    String userID;
    ArrayList<String> userNames = new ArrayList<>();
    ArrayList<String> uid = new ArrayList<>();
    String receiverUID,receivername;


    //Overriden method onCreateView
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.tab1, container, false);

        //get firebase auth instance
        auth = FirebaseAuth.getInstance();

        //get current user
        final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();



       authListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();
                if (user == null) {
                    // user auth state is changed - user is null
                    // launch login activity
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                    getActivity().finish();
                }
            }
        };

        mDatabase = FirebaseDatabase.getInstance().getReference().child("users");
        mDatabase.keepSynced(true);
        listView = (ListView) v.findViewById(R.id.listview);

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

                //User user = dataSnapshot.getValue(User.class);
                //Get map of users in datasnapshot
                collectUserNames((Map<String, Object>) dataSnapshot.getValue());
            }


            @Override
            public void onCancelled(DatabaseError databaseError) {
                //Error in Reaching Database
                Log.d("TAB1","tab1 error");
            }


        } );


        //Getting username from listview
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            public void onItemClick(AdapterView<?> a, View v, int position,
                                    long id) {
                String s =Integer.toString(position);
                receiverUID = uid.get(position);
                receivername = userNames.get(position);

                Toast.makeText(getContext(),s , Toast.LENGTH_SHORT).show();
                Log.v("log_tag", "List Item Click");
                 NewReminder();
            }
        });





        //Returning the layout file after inflating
        //Change R.layout.tab1 in you classes

        return v;
    }

    private void collectUserNames(Map<String, Object> users) {



        //iterate through each user, ignoring their UID
        for (Map.Entry<String, Object> entry : users.entrySet()){

            //Get user map
            Map singleUser = (Map) entry.getValue();
            //Getting UID of every user and adding to the Array
            String Key = entry.getKey();
            Log.d("KEy Value",Key);
            //Removing the Current User's ID from the Display List

            if(!Key.equals(userID)) {
                uid.add(Key);


                //Get usernames and append to list and array
                userNames.add((String) singleUser.get("username"));
            }
           //Display all usernames
            ArrayAdapter adapter = new ArrayAdapter(getContext(), android.R.layout.simple_list_item_1, userNames);
            listView.setAdapter(adapter);
        }


    }

Find my current Firebase Database Model Here

KENdi
  • 7,576
  • 2
  • 16
  • 31
shivam dhuria
  • 69
  • 1
  • 9

1 Answers1

0

First of All you have to get the all contacts from clients device,

Note : You Have to Check For Contacts Permissions by your self & don't Forgot to add Permissions in Manifest.

Call initData() in onCreate or After Checking Permissions.

here is the code to get Contacts from Clients Device.

private void initData() {
    Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null,null);
    while(Objects.requireNonNull(cursor).moveToNext()){
        String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
        String number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
        // Finds the contact in our database through the Firebase Query to know whether that contact is using our app or not.
        findUsers(number);
    }
}

While Getting Each Contact one by one from clients device, simultaneously we will trigger the firebase query to check whether that contact is using our app or not.

So we are using "findUser" Method to check whether that contact is using our app or not.

private void findUsers(final String number){
    Query query = FirebaseDatabase.getInstance().getReference()
            .child("User")
            .orderByChild("phone")
            .equalTo(number);

    query.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            if (snapshot.getValue() != null){
                Map<String, Object> map = (Map<String, Object>) snapshot.getValue();
                // this will print whole map of contacts who is using our app from clients contacts.
                Log.d("ContactSync", snapshot.getValue().toString());
                // so you can use any value from map to add it in your Recycler View.
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {
            Log.d("ContactSync", error.getMessage());
        }
    });
}

Here is how my database structure looks like. database structure image

Thanks for reading this answer, I hope this will be helpful!

Kamal Panara
  • 482
  • 7
  • 16