Below is the structure of my Firebase Realtime Database:
I want to get Contacts from the phone in which the app is running. Then I want to check if any of the contact's phone number is in the database. Or in other words, if a user with that particular number exists or not. If it exists, I want to put the contact in a HashMap whose key is the number and name is the value. I will later add this HashMap data to RecyclerView.
I am able to get the contacts and also check the above condition, but it does not add them to the HashMap. Below is my code for getting contacts and checking:
@SuppressLint("Range")
private void getContacts() {
@SuppressLint("Recycle")
Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, null, null, null);
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
number = number.trim();
Pattern p = Pattern.compile(
"^(\\+\\d{1,3}( )?)?((\\(\\d{1,3}\\))|\\d{1,3})[- .]?\\d{3,4}[- .]?\\d{4}$");
Matcher m = p.matcher(number);
if (m.find()) {
if (exists(number).equalsIgnoreCase(number)) {
Log.i("Does match:", number);
contactList.put(number, name);
} else {
Log.wtf("Does not match:", number);
}
}
}
}
private String exists(String number) {
final String[] numberF = {""};
if (number.length() > 10 && number.length() <= 15) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("users");
reference.child(number).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
String numberDB = snapshot.child("number").getValue(String.class);
numberF[0] = numberDB;
} else {
numberF[0] = "";
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
numberF[0] = "";
}
});
} else {
numberF[0] = "";
}
return numberF[0];
}
Please help me out to check the above condition or tell why it is not added to the HashMap.