首页 > 解决方案 > 如何从firebase获取电话号码

问题描述

我尝试将我的电话簿与已有帐户的联系人进行比较。

我设法将电话簿显示到 Recycler View 中,但是当我尝试与 Firebase 进行比较时,什么都没有显示。

主要目的是只显示使用该应用程序的联系人。

带调试:DataSnapshot { key = Users, value = null }

在此处输入图像描述

    private void getContactList() {

    Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);

    assert phones != null;
    while (phones.moveToNext()) {

        String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));

        String phone = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

        Contacts mContacts = new Contacts(name, phone);
        contactsList.add(mContacts);
        Collections.sort(contactsList, new Contacts(name, phone));

        getUserInfo(mContacts);
    }
}

private void getUserInfo(Contacts mContact) {

    DatabaseReference mUserDB = FirebaseDatabase.getInstance().getReference().child("Users");

    Query query = mUserDB.orderByChild("phone").equalTo(mContact.getPhone());

    query.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            if (dataSnapshot.exists()) {

                String phone = "";
                String name = "";

                for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {

                    if (childSnapshot.child("phone").getValue() != null)

                        phone = dataSnapshot.child("phone").getValue().toString();
                    Log.i(TAG, "phone ---------+++++++++++//////////////////" + phone);

                    if (childSnapshot.child("name").getValue() != null)

                        name = childSnapshot.child("name").getValue().toString();

                    Contacts mUser = new Contacts(name, phone);
                    userList.add(mUser);
                    mUserListAdapter.notifyDataSetChanged();
                    Collections.sort(userList, new Contacts(name, phone));
                    return;


                }
            }
        }

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

            String err = databaseError.toString();

            Toast.makeText(mContext, "error" + err, Toast.LENGTH_SHORT).show();
            Log.i(TAG, "err------------+++++++++++++++++++----------------" + err);
        }
    });
}               

标签: androidfirebasefirebase-realtime-database

解决方案


您在UserPhone代码中缺少 JSON 的级别。

所以像:

if (childSnapshot.child("UserPhone/phone").getValue() != null)

    phone = dataSnapshot.child("UserPhone/phone").getValue().toString();
    ...

或者更地道一点:

DataSnapshot phoneSnapshot = childSnapshot.child("UserPhone/phone");
if (phoneSnapshot.exists())
    phone = phoneSnapshot.getValue(String.class);
    ...

推荐阅读