简体   繁体   中英

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. 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.

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. 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.

"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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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