android - 如何从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);
}
});
}
解决方案
您在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);
...
推荐阅读
- file-upload - 如何更改 AOLServer/CentOS 6 上文件上传的最大大小?
- python - 如何更新数组中多个对象的属性值
- python - 如何使用远程驱动程序在 selenium 中验证代理
- javascript - React 功能组件:clearInterval() 没有清除我的间隔
- c++11 - 将参数从“const_Ty”转换为 const 自定义结构时出错
- c++ - 与类相关以及为什么代码会出错
- sql-server-2008 - 无法使用电子将数据表单插入到 sql server
- mysql - 如何将 XML 中某些属性的值相加?
- reactjs - 无法解析链接中的对象 ID
- regex - 使用 Regex 组合分隔数据