简体   繁体   English

无法将数据保存到firebase实时数据库中,只有图像被保存到存储中

[英]Can't save data into firebase realtime database, only image was save to storage

I can't save data into firebase realtime database but I was able to save the images into firebase storage.我无法将数据保存到 firebase 实时数据库中,但我能够将图像保存到 firebase 存储中。 I have used Toast to check if my ref.push.key() generates a key and it does so ref.child(refKey).setValue(Object) should insert my data into realtime database, but It does not insert the data at all.我用 Toast 检查我的 ref.push.key() 是否生成了一个密钥,它这样做了 ref.child(refKey).setValue(Object) 应该将我的数据插入实时数据库,但它根本不插入数据.

My firebase reference:我的火力基地参考:

        mStorageRef = FirebaseStorage.getInstance().getReference("products_uploads");
        mDatabaseRef = FirebaseDatabase.getInstance().getReference("products_uploads");

Method should have save to realtime and storage, but it only save to storage:方法应该有保存到实时和存储,但它只保存到存储:

    private void uploadFile() {
    if (mImageUri != null) {
        StorageReference fileReference = mStorageRef.child(System.currentTimeMillis()
                + "." + getFileExtension(mImageUri));

        uploadProgressBar.setVisibility(View.VISIBLE);
        uploadProgressBar.setIndeterminate(true);

        mUploadTask = fileReference.putFile(mImageUri)
                .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot> () {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        Handler handler = new Handler();
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                uploadProgressBar.setVisibility(View.VISIBLE);
                                uploadProgressBar.setIndeterminate(false);
                                uploadProgressBar.setProgress(0);
                            }
                        }, 500);

                        Toast.makeText(UploadActivity.this, "Product  Upload successful", Toast.LENGTH_LONG).show();
                        fileReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                            @Override
                            public void onSuccess(Uri uri) {
                                Uri downloadUrl = uri;

                                Product upload = new Product(nameEditText.getText().toString().trim(),
                                        downloadUrl.toString(),
                                        descriptionEditText.getText().toString(),
                                        priceEditText.getText().toString().trim(),
                                        quantityEditText.getText().toString().trim());

                                String uploadId = mDatabaseRef.push().getKey(); // was able to generate key                               
                                mDatabaseRef.child(uploadId).setValue(upload)
                                        .addOnSuccessListener(new OnSuccessListener<Void>() {
                                            @Override
                                            public void onSuccess(Void unused) {

                                                Toast.makeText(UploadActivity.this, "Inserted to realtime db", Toast.LENGTH_LONG).show();

                                            }
                                        })
                                        .addOnFailureListener(new OnFailureListener() {
                                            @Override
                                            public void onFailure(@NonNull Exception e) {

                                                Toast.makeText(UploadActivity.this, "Exception realtime db"+e, Toast.LENGTH_LONG).show();

                                            }
                                        }); 

                               uploadProgressBar.setVisibility(View.INVISIBLE);
                                openImagesActivity ();                                }
                        });
                    }
                })
                .addOnFailureListener(new OnFailureListener () {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        uploadProgressBar.setVisibility(View.INVISIBLE);
                        Toast.makeText(UploadActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                })
                .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot> () {
                    @Override
                    public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                        double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
                        uploadProgressBar.setProgress((int) progress);
                    }
                });
    } else {
        Toast.makeText(this, "You haven't Selected Any file selected", Toast.LENGTH_SHORT).show();
    }
}

Realtime database structure实时数据库结构

在此处输入图像描述

Storage database structure存储数据库结构

在此处输入图像描述

I've added completion listener to my setValue, but it does call onSuccess() or onFailure() as both of Toast does not display.我在 setValue 中添加了完成侦听器,但它确实调用了 onSuccess() 或 onFailure(),因为 Toast 都没有显示。 Please advice, thank you.请指教,谢谢。

Also, I noticed the following on log:另外,我在日志中注意到以下内容:

Firebase Database connection was forcefully killed by the server. Will not attempt reconnect. Reason: Database lives in a different region. Please change your database URL to https://crud-94fb7-default-rtdb.asia-southeast1.firebasedatabase.app

However both realtime and storage are under southeast1, also I checked google-services.json file and it has the correct database URL.但是实时和存储都在东南1下,我还检查了 google-services.json 文件,它具有正确的数据库 URL。

"project_info": { "project_number": "1056142426280", "firebase_url": "https://crud-94fb7-default-rtdb.asia-southeast1.firebasedatabase.app", "project_id": "crud-94fb7", "storage_bucket": "crud-94fb7.appspot.com" },

Full log:完整日志:

05/31 11:40:52: Launching 'app' on Xiaomi Redmi K30.
App restart successful without requiring a re-install.
$ adb shell am start -n "com.example.morales/com.example.morales.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 27706 on device 'xiaomi-redmi_k30-a1bff4e'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/Perf: Connecting to perf service.
I/FirebaseApp: Device unlocked: initializing all Firebase APIs for app [DEFAULT]
I/FirebaseInitProvider: FirebaseApp initialization successful
I/FeatureParser: can't find phoenix.xml in assets/device_features/,it may be in /system/etc/device_features
E/libc: Access denied finding property "ro.vendor.df.effect.conflict"
W/example.morales: type=1400 audit(0.0:393296): avc: denied { read } for name="u:object_r:vendor_displayfeature_prop:s0" dev="tmpfs" ino=27284 scontext=u:r:untrusted_app:s0:c134,c257,c512,c768 tcontext=u:object_r:vendor_displayfeature_prop:s0 tclass=file permissive=0
E/Perf: Fail to get file list com.example.morales
    getFolderSize() : Exception_1 = java.lang.NullPointerException: Attempt to get length of null array
E/Perf: Fail to get file list com.example.morales
    getFolderSize() : Exception_1 = java.lang.NullPointerException: Attempt to get length of null array
    Fail to get file list oat
    getFolderSize() : Exception_1 = java.lang.NullPointerException: Attempt to get length of null array
I/AdrenoGLES: QUALCOMM build                   : 663be55, I724753c5e3
    Build Date                       : 11/06/19
    OpenGL ES Shader Compiler Version: EV031.27.05.02
    Local Branch                     : mybranchea006718-00ab-f18a-9c1c-5cb90179c3e0
    Remote Branch                    : quic/gfx-adreno.lnx.1.0.r84-rel
    Remote Branch                    : NONE
    Reconstruct Branch               : NOTHING
    Build Config                     : S P 8.0.12 AArch64
I/AdrenoGLES: PFP: 0x016ee187, ME: 0x00000000
W/AdrenoUtils: : Failed to open /sys/class/kgsl/kgsl-3d0/gpu_model
    : Failed to read chip ID from gpu_model. Fallback to use the GSL path
W/RenderThread: type=1400 audit(0.0:393297): avc: denied { search } for name="kgsl" dev="sysfs" ino=47468 scontext=u:r:untrusted_app:s0:c134,c257,c512,c768 tcontext=u:object_r:sysfs_kgsl:s0 tclass=dir permissive=0
W/Gralloc3: mapper 3.x is not supported
I/Timeline: Timeline: Activity_launch_request time:274548146
W/ActivityThread: handleWindowVisibility: no activity for token android.os.BinderProxy@74d94aa
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
I/AssistStructure: Flattened final assist data: 2676 bytes, containing 1 windows, 14 views
W/PersistentConnection: pc_0 - Firebase Database connection was forcefully killed by the server. Will not attempt reconnect. Reason: Database lives in a different region. Please change your database URL to https://crud-94fb7-default-rtdb.asia-southeast1.firebasedatabase.app
I/Timeline: Timeline: Activity_launch_request time:274562051
W/Settings: Setting airplane_mode_on has moved from android.provider.Settings.System to android.provider.Settings.Global, returning read-only value.
W/StorageUtil: no auth token for request
W/NetworkRequest: no auth token for request
    No App Check token for request.
W/StorageUtil: no auth token for request
W/NetworkRequest: no auth token for request
    No App Check token for request.
D/UploadTask: Increasing chunk size to 524288
W/StorageUtil: no auth token for request
W/NetworkRequest: no auth token for request
    No App Check token for request.
D/UploadTask: Increasing chunk size to 1048576
W/StorageUtil: no auth token for request
W/NetworkRequest: no auth token for request
W/NetworkRequest: No App Check token for request.
W/StorageUtil: no auth token for request
W/NetworkRequest: no auth token for request
    No App Check token for request.
I/Toast: Show toast from OpPackageName:com.example.morales, PackageName:com.example.morales
I/Timeline: Timeline: Activity_launch_request time:274573441
W/ActivityThread: handleWindowVisibility: no activity for token android.os.BinderProxy@c3f8da0
I/Timeline: Timeline: Activity_launch_request time:274595122
W/ActivityThread: handleWindowVisibility: no activity for token android.os.BinderProxy@6fa9b90

事实证明,重建项目解决了这个问题,但我从昨晚开始就没有睡觉。

尝试:清理应用程序,然后重新构建

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM