如何显示客户通讯录中仅已注册的联系人列表(在Firebase上)(通过电话号码) [英] How do I display list of only registered contacts(on firebase) from a client's address book(via phone numbers)

查看:64
本文介绍了如何显示客户通讯录中仅已注册的联系人列表(在Firebase上)(通过电话号码)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的是搜索客户的通讯录(电话号码),并仅通过查看其电话号码是否已注册来显示在Firebase上注册的联系人.(类似于Whatsapp)

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)

当前,我正在显示所有在Firebase上的注册用户

Currently I am displaying all the registered users on firebase

代码:

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);
        }


    }

找到我当前的Firebase数据库模型 在这里

Find my current Firebase Database Model Here

推荐答案

首先,您必须从客户端设备获取所有联系人,

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

注意:您必须自行检查联系人权限.不要忘记添加权限清单.

在onCreate或检查权限后调用initData().

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);
    }
}

从客户端设备一个接一个地联系每个联系人的同时,我们将触发firebase查询,以检查该联系人是否正在使用我们的应用.

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.

因此,我们正在使用"findUser"检查该联系人是否正在使用我们的应用程序的方法.

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.

感谢您阅读此答案, 我希望这会有所帮助!

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

这篇关于如何显示客户通讯录中仅已注册的联系人列表(在Firebase上)(通过电话号码)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆