java - 在添加之前检查 Firebase 数据库中是否存在 URL

标签 java android firebase firebase-realtime-database

我正在尝试将图片上传到 Firebase 存储,并使用 getDownloadUrl() 方法将下载 URL 添加到 Firebase 数据库

我想在添加之前检查该 URL 是否已存在于 Firebase 数据库 中,我尝试使用 StringUtils.substringBetween(mUrl, "%2F", ".png");例如:

https://firebasestorage.googleapis.com/v0/b/app.appspot.com/o/Frames%2FAPP1565024974054.png

拆分后我得到这个文件的名称:

APP1565024974054.png

所以我可以在添加之前检查这个字符串是否存在于数据库中。

这是我的代码:

gettingURLs 方法:从数据库中获取所有的URL,并将它们添加到ArrayList。

private void gettingURLs(String mUrl) {
        ArrayList<String> arrayList = new ArrayList<>();
        mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot ds : dataSnapshot.getChildren()) {
                    String url = ds.child("url").getValue(String.class);
                    arrayList.add(url);
                }
                verification(arrayList, mUrl);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Toast.makeText(createFrame.this, "Ops !,Something went wrong", Toast.LENGTH_SHORT).show();
            }
        });
    }

验证方法:检查URL是否存在

   private void verification(ArrayList<String> arrayList, String mUrl) {
        if (arrayList.size() > 0) {
            String PREFIX = StringUtils.substringBetween(mUrl, "%2F", ".png");
            for (String str : arrayList) {
                if (str.trim().contains(PREFIX)) {
                    Toast.makeText(createFrame.this, "Frame already uploaded, You don't need to upload it again", Toast.LENGTH_SHORT).show();
                    Helper.dismissProgressDialog();
                    break;
                } else {
                    addUrlToDataBase(mUrl, mDatabase);
                    break;
                }
            }
        } else
            addUrlToDataBase(mUrl, mDatabase);
    }

我的问题:

上面的代码添加了所有 URL,尽管它已经存在于数据库中,我如何在添加之前检查 URL 是否存在

1 - 如果 URL 存在,用

显示 Toast
Toast.makeText(createFrame.this, "Frame already uploaded, You don't need to upload it again", Toast.LENGTH_SHORT).show();

2 - 如果URL不存在,则正常添加

最佳答案

每次将图像上传到 Firebase 存储时,您都可以选择生成一个 downloadUrl。 这个下载 url 是唯一的,这意味着如果您再次上传相同的图片,您将获得不同的 url。因此,比较 downloadUrls 是一个坏主意,因为它们永远不会匹配。 p>

但是,您可以通过一种方法操作文件名来检查文件是否已存在于 Firebase 存储中。只需创建一个包含文件名的引用,然后尝试获取下载 URL(在推送之前)。如果文件不存在,则响应将为 null。这是一个小例子:

void getReferenceAndLoadNewBackground(String photoName) {

    // edit this path to fit your own existing structure
    final StorageReference storageReference = FirebaseStorage.getInstance().getReference().child("photos").child(photoName + ".png");

    /* Now, here's where the big deal is.
     * If the image exists, onSuccess would be called.
     * If the image does not exist, onFailure would be called but you'll still need to get the particular error. */
    storageReference.getDownloadUrl()
        .addOnSuccessListener(new OnSuccessListener<Uri>() {
            @Override
            public void onSuccess(Uri uri) {
                // Yaay, the image exists, no need to re-upload.
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception exception) {
                // this does not necessarily mean the image does not exist, we still need to check the error code
                int code = ((StorageException) exception).getErrorCode();
                if (code == StorageException.ERROR_OBJECT_NOT_FOUND) {

                    // haha, the image does not actually exist, upload it
                }
                else {
                    // handle all other problems here
                }

            }
        });
}

要了解有关getDownloadUrl() 函数的更多信息,您可以查看this post。或阅读 the documentation .

希望对您有所帮助。编码愉快!

关于java - 在添加之前检查 Firebase 数据库中是否存在 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57374755/

相关文章:

java - JPA getSingleResult() 或 null

android - 使用 `device offline` 命令时,Nexus 5 显示 `adb shell`

Android Edit text onclicklistener 在第一次点击时不起作用

android - 将 Realm 数据库放置在 SD 卡上并从那里使用它 - Android

firebase - 将来自 Firebase 和 Google 分析的数据合并到 1 个 View 中

java - 如何统计字符串中括号(包括括号)的内容

java - 正则表达式匹配至少 2 个数字,字符串中任意顺序的 2 个字母

java - 应用程序未从 Firestore 检索文档

java - Spring Java 应用程序找不到 keystore 文件

android - Android 中的 Firebase 分页