java - 我的 Firestore 项目集合中的文档重复

标签 java android google-cloud-firestore

我已将我的应用链接到 firestore。每次应用程序启动时,所有联系人都会在集合中复制,即使联系人的值相同也是如此。但是,在 ListView 中,联系人被覆盖了。如果在我的应用程序中错误地删除了联系人,我想同步连接到同一 firestore 数据库本身的另一个应用程序的所有联系人。

 if (cursor.getCount() > 0) {
                    while (cursor.moveToNext()) {
                        ContactModel cm = new ContactModel();
                        cm.id = cursor.getString(cursor.getColumnIndex(_ID));
                        cm.names = cursor.getString(cursor.getColumnIndex(DISPLAY_NAME));
                        int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(HAS_PHONE_NUMBER)));
                        if (hasPhoneNumber > 0) {

                            Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[]{cm.id}, null);


                            while (phoneCursor.moveToNext()) {
                                phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
                                cm.mobileNumber = phoneNumber;


                            }
                            phoneCursor.close();
                            Map<String, Object> contactList = new HashMap<>();
                            contactList.put("contact_id", cm.id);
                            contactList.put("contact_name", cm.names);
                            contactList.put("contact_mobileNumber", cm.mobileNumber);
                            db.collection("Contacts").add(contactList);


                        }
                        contacts.add(cm);


                    }

                    cursor.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
            return contacts;

    }

最佳答案

我刚刚解决了这个问题。只需将调用将所有联系人加载到数据库中的特定方法放在 onRequestPermissionsResult() 而不是 onCreate() 中。

public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults) {
        if (requestCode == PERMISSIONS_REQUEST_READ_CONTACTS) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                loadContactList();
                loadListView();
                loadContactsIntoDb();
            } else {
                Toast.makeText(this, "Until you grant the permission, we canot display the list", Toast.LENGTH_SHORT).show();
            }
        }
    }

关于java - 我的 Firestore 项目集合中的文档重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54305411/

相关文章:

android GridView 从右到左放置项目

android - Meteor - 安装 android 平台找不到 ANDROID_HOME 变量

java - 返回当前的 android 布局或屏幕宽度以进行调试

java - 如何在spring框架中设计bean

java - 如果我需要在开始时评估条件,有没有办法避免 while(true) ?

swift - 如何将 Firestore 文档映射到结构?

javascript - 子属性(子集合)上的 firestore orderby

dart - Flutter Firestore startAt() endtAt() 在 orderby 字符串值时不起作用

javascript - 循环中的 jQuery 元素

java - iMacros 框架名称疑难解答