【问题标题】:Real time Database of Firebase not working from android studio i can't able to upload on it?Firebase 的实时数据库无法在 android studio 中运行,我无法上传?
【发布时间】:2020-12-22 10:34:47
【问题描述】:

我已经修复了firebase实时数据库的读写规则,但我仍然无法对其进行读写。

{
  "rules": {
    ".read": "true",
    ".write": "true"
  }
}

我也试过这个:

{
  "rules": {
    ".read": true,
    ".write": true
  }
}

Firebase 存储规则:

    rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if true;
    }
  }
}

Firebase 存储规则工作正常,因为图像已上传并调用 onSuccessListener。

我用来在数据库上设置值的代码如下所示, 我已经将引用定义为:

    storageReference = FirebaseStorage.getInstance().getReference("Events_Details");
    databaseReference = FirebaseDatabase.getInstance().getReference("Events_Details");

    private void uploadUserInformationToDatabase() {
        progressDialog.show();
        if (image_uri != null) {

            //this will create a big_number.jpg and when we call .child this means we are
            //going to add something inside Events_Images Directory
            StorageReference fileReference = storageReference.child(System.currentTimeMillis() + "." + getFileExtension(image_uri));

            uploadTask = fileReference.putFile(image_uri)
                    .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                            //Now we need to get the url of the image that you have uploaded.
                            Task<Uri> uri = taskSnapshot.getStorage().getDownloadUrl();
                            while (!uri.isComplete());
                            String url = uri.getResult().toString();
                            createUserEvent.setImageUrl(url);

                            //now we will save this object in our database
                            String uploadId = databaseReference.push().getKey();
                            databaseReference.child(uploadId)
                                             .setValue(createUserEvent);
                            progressDialog.dismiss();

                            Toast.makeText(context, "Event Created Successfully", Toast.LENGTH_SHORT).show();
                        }
                    })
                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
                            progressDialog.dismiss();
                        }
                    });

        } else {
            progressDialog.dismiss();
            Toast.makeText(context, "No File Selected", Toast.LENGTH_SHORT).show();
        }
    }

Toast for Event Created 每次都成功显示,并且图像也被上传到存储中,但对象没有保存在实时数据库中。 CreateUserEvent 只是一个类,我想将它的对象与我将上传到存储的图像一起保存到实时数据库中。图像总是在firebase存储上上传成功,在它调用onSuccess函数之后,在onSuccess函数内部我编写了对象代码以保存在实时数据库中,但这不起作用。请帮我解决它我已经浪费了2我的几天,但无法解决这个问题。

【问题讨论】:

标签: android firebase firebase-realtime-database firebase-storage rules


【解决方案1】:

好的......我已经试过你的代码了。下面是修改后的函数:

databaseReference = FirebaseDatabase.getInstance().getReference();

private void uploadUserInformationToDatabase() {
        progressDialog.show();

        if (image_uri != null) {

            //this will create a big_number.jpg and when we call .child this means we are
            //going to add something inside Events_Images Directory
            StorageReference fileReference = storageReference.child(System.currentTimeMillis() + "." + getFileExtension(image_uri));

            //now we will store our image file in firebase and check for success and failure events
            //And we store the refrence of current process in this uploadtask varriable which helps us
            //when user clicks on upload button multiple time, so when he clicks one time uploadTask will
            //take  the reference and when the upload runnig and the user clicks the upload button another
            //time then we put a check if uploadTask is null or not. it is null then this means no task is
            //running else we don't upload. This check you put above in upload onlicklisterner.


            uploadTask = fileReference.putFile(image_uri)
                    .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

//                            lets create the object with name and url of the image and save this object into our database.
//                            String name_of_event = file_name.getText().toString().trim();
//                            String url_of_image = taskSnapshot.getMetadata().getReference().getDownloadUrl().toString();
//                            Upload upload = new Upload(name_of_event, url_of_image);



                            //Now you just need to get the url of the image that you have uploaded.

                            Task<Uri> uri = taskSnapshot.getStorage().getDownloadUrl();
                            while (!uri.isComplete()) ;
                            String url = uri.getResult().toString();
                            createUserEvent.setImageUrl(url);

                            //now we will save this object in our database
                            String uploadId = databaseReference.push().getKey();
                            Log.d(TAG, "onSuccess: Going To Save Object To Firebase");
                            Log.d(TAG, "onSuccess: UPLOAD ID : "+uploadId);

                            databaseReference.child("Event Details").child(uploadId).setValue(createUserEvent).addOnCompleteListener(new OnCompleteListener<Void>() {
                                @Override
                                public void onComplete(@NonNull Task<Void> task) {
                                    Toast.makeText(context, "Data uploaded successfully", Toast.LENGTH_SHORT).show();
                                    progressDialog.dismiss();
                                }
                            }).addOnFailureListener(new OnFailureListener() {
                                @Override
                                public void onFailure(@NonNull Exception e) {
                                    Toast.makeText(context, "Failed to upload data", Toast.LENGTH_SHORT).show();
                                    progressDialog.dismiss();
                                }
                            });
                        }
                    });
        } else {
            progressDialog.dismiss();
            Toast.makeText(context, "No File Selected", Toast.LENGTH_SHORT).show();
        }
    }

我在上传到数据库时取得了成功。请立即检查您的数据库。

【讨论】:

  • 我已经添加了我的存储规则。
  • uploadId 是来自 firebase 吗?通过 toast 进行测试。@shivanshshrivastava
  • 请放一张你的数据库截图。我认为 getReference() 中的传递参数导致了问题。请提供数据库截图。
  • 我已经添加了截图。databaseReference 的 onSuccessListener 我不知道如何使用它。我会用谷歌搜索它并很快为您提供控制台日志。我在 logcat 上显示的上传 ID。
  • 您在 getReference() 中的参数导致了问题。
【解决方案2】:

StorageReference 文件路径=storageReference.child("Blogimage").child(System.currentTimeMillis()+ "." +getFileEXt(imageuri)); //uploadTask=filepath.putFile(imageuri);

               filepath.putFile(imageuri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                   @Override
                   public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                     // String downlod = taskSnapshot.getMetadata().getReference().getDownloadUrl().toString();
                       if (taskSnapshot.getMetadata() != null) {
                           if (taskSnapshot.getMetadata().getReference() != null) {
                               Task<Uri> result = taskSnapshot.getStorage().getDownloadUrl();
                               result.addOnSuccessListener(new OnSuccessListener<Uri>() {
                                   @Override
                                   public void onSuccess(Uri uri) {
                                       String imageUrl = uri.toString();
                                       DatabaseReference newpost=databaseReference.push();
                                       Map<String , String > profile =new HashMap<>();
                                       profile.put("name",name);
                                       profile.put("prof",prof);
                                       profile.put("location",location);
                                       profile.put("email",mail);
                                       profile.put("web",web);
                                       profile.put("uid",user.getUid());
                                       profile.put("url",imageUrl);

                                       allUserMember.setName(name);
                                       allUserMember.setUid(auth.getUid());

                                       allUserMember.setProf(prof);
                                       allUserMember.setLocation(location);

                                       allUserMember.setUrl(imageUrl);
                                       newpost.setValue(profile);
                                       newpost.child(user.getUid()).setValue(allUserMember);
                                       documentReference.set(profile).addOnSuccessListener(new OnSuccessListener<Void>() {
                                           @Override
                                           public void onSuccess(Void unused) {

                                               Snackbar.make(findViewById(android.R.id.content),"Image uplode",Snackbar.LENGTH_LONG).show();
                                               pd.dismiss();
                                               Toast.makeText(CreateProfile1.this, "it work", Toast.LENGTH_SHORT).show();
                                           }
                                       });
                                       //createNewPost(imageUrl);
                                   }
                               });
                           }
                       }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-11
    • 2020-10-16
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 2021-04-14
    • 2021-11-01
    • 1970-01-01
    相关资源
    最近更新 更多