我面临 HashMaps 对象之一未存储在 Firebase 数据库中的问题。 HashMap 的对象 put 方法之一没有被存储

问题描述 投票:0回答:1

当我尝试将数据存储在 Firebase 实时数据库中时,除了一个对象之外的所有其他对象都会被存储,即

 postsMap.put("postimage", downloadUrl);
,这一特定数据不会存储在 Firebase 实时数据库中,其余所有其他数据都会被存储。

这是我的 PostActivity.java 代码 -

``


     import android.app.ProgressDialog;
    import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
> import android.view.MenuItem;
> import android.view.View;
> import android.widget.Button;
> import android.widget.EditText;
> import android.widget.ImageButton;
> import android.widget.Toast;
> 
> import androidx.annotation.NonNull;
> import androidx.annotation.Nullable;
> import androidx.appcompat.widget.Toolbar;
> 
> import androidx.activity.EdgeToEdge;
> import androidx.appcompat.app.AppCompatActivity;
> import androidx.core.graphics.Insets;
> import androidx.core.view.ViewCompat;
> import androidx.core.view.WindowInsetsCompat;
> 
> import com.google.android.gms.tasks.OnCompleteListener;
> import com.google.android.gms.tasks.OnSuccessListener;
> import com.google.android.gms.tasks.Task;
> import com.google.firebase.auth.FirebaseAuth;
> import com.google.firebase.database.DataSnapshot;
> import com.google.firebase.database.DatabaseError;
> import com.google.firebase.database.DatabaseReference;
> import com.google.firebase.database.FirebaseDatabase;
> import com.google.firebase.database.ValueEventListener;
> import com.google.firebase.storage.FirebaseStorage;
> import com.google.firebase.storage.StorageReference;
> import com.google.firebase.storage.UploadTask;
> 
> import java.text.SimpleDateFormat;
> import java.util.Calendar;
> import java.util.HashMap;
> 
> public class PostActivity extends AppCompatActivity {
> 
> private Toolbar mToolbar;
> 
> private ProgressDialog loadingBar;
> private ImageButton SelectPostImage;
> private Button UpdatePostButton;
> 
> private EditText PostDescription;
> 
> private static final int Gallery_Pick = 1;
> 
> private Uri ImageUri;
> 
> private String Description;
> 
> private StorageReference PostsImagesReference;
> 
> private DatabaseReference UsersRef, PostsRef;
> 
> private FirebaseAuth mAuth;
> 
> private String saveCurrentDate, saveCurrentTime, postRandomName,downloadUrl, current_user_id;
> 
> 
> 
> >     @Override
> protected void onCreate(Bundle savedInstanceState) {
> super.onCreate(savedInstanceState);
> 
> setContentView(R.layout.activity_post);
> 
> mAuth = FirebaseAuth.getInstance();
> current_user_id = mAuth.getCurrentUser().getUid();
> 
> PostsImagesReference = FirebaseStorage.getInstance().getReference();
> UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
> PostsRef = FirebaseDatabase.getInstance().getReference().child("Posts");
> 
> SelectPostImage = findViewById(R.id.select_post_image);
> UpdatePostButton = findViewById(R.id.update_post_button);
> PostDescription = findViewById(R.id.post_description);
> loadingBar = new ProgressDialog(this);
> 
> 
> 
> 
> mToolbar = findViewById(R.id.update_post_page_toolbar);
> setSupportActionBar(mToolbar);
> getSupportActionBar().setDisplayHomeAsUpEnabled(true);
> getSupportActionBar().setDisplayShowHomeEnabled(true);
> getSupportActionBar().setTitle("Update Post");
> 
> 
> 
> SelectPostImage.setOnClickListener(new View.OnClickListener() {
> >             @Override
> public void onClick(View v) {
> 
> OpenGallery();
> 
> >             }
> >         });
> 
> 
> UpdatePostButton.setOnClickListener(new View.OnClickListener() {
> >             @Override
> public void onClick(View v) {
> 
> ValidatePostInfo();
> 
> >             }
> >         });
> 
> 
> 
> >     }
> 
> private void ValidatePostInfo() {
> 
> Description = PostDescription.getText().toString();
> 
> if(ImageUri == null)
> >         {
> Toast.makeText(this,"Please select post image",Toast.LENGTH_LONG).show();
> else if (TextUtils.isEmpty(Description)) {
> 
> Toast.makeText(this,"Please say something about your image",Toast.LENGTH_LONG).show();
> 
> >         }
> else
> >         {
> loadingBar.setTitle("Add New Post");
> loadingBar.setMessage("Please wait, while we are creating your new post....");
> loadingBar.show();
> loadingBar.setCanceledOnTouchOutside(true);
> StoringImageToFirebaseStorage();
> >         }
> 
> >     }
> 
> private void StoringImageToFirebaseStorage() {
> 
> 
> Calendar callForDate = Calendar.getInstance();
> SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
> saveCurrentDate = currentDate.format(callForDate.getTime());
> 
> 
> Calendar callForTime = Calendar.getInstance();
> SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm");
> saveCurrentTime = currentTime.format(callForDate.getTime());
> 
> postRandomName = saveCurrentDate + saveCurrentTime;
> 
> 
> StorageReference filePath = PostsImagesReference.child("Post Images").child(ImageUri.getLastPathSegment() + postRandomName + ".jpg");
> 
> 
> 
> 
> filePath.putFile(ImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
> >                             @Override
> public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
> 
> 
> if(task.isSuccessful())
> >                                 {
> filePath.putFile(ImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
> >                                         @Override
> public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
> filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
> >                                                 @Override
> public void onSuccess(Uri uri) {
> downloadUrl =  uri.toString();
> 
> >                                                 }
> >                                             });
> >                                         }
> >                                     });
> 
> 
> Toast.makeText(PostActivity.this,"Image uploaded successfully to storage", Toast.LENGTH_LONG).show();
> 
> SavingPostInformationToDatabase();
> 
> >                                 }
> else
> >                                 {
> String message = task.getException().getMessage();
> Toast.makeText(PostActivity.this,"Error Occured: " + message, Toast.LENGTH_LONG).show();
> >                                 }
> 
> >                             }
> >                         });
> 
> 
> 
> 
> 
> >     }
> 
> private void SavingPostInformationToDatabase() {
> 
> UsersRef.child(current_user_id).addValueEventListener(new ValueEventListener() {
> >             @Override
> public void onDataChange(@NonNull DataSnapshot snapshot) {
> 
> if(snapshot.exists())
> >                 {
> String userFullName = snapshot.child("fullname").getValue().toString();
> String userProfileImage = snapshot.child("profileimage").getValue().toString();
> 
> HashMap postsMap = new HashMap();
> postsMap.put("uid", current_user_id);
> postsMap.put("date", saveCurrentDate);
> postsMap.put("time", saveCurrentTime);
> postsMap.put("description", Description);
> postsMap.put("postimage", downloadUrl);
> postsMap.put("profileimage",userProfileImage);
> postsMap.put("fullname", userFullName);
> 
> PostsRef.child(current_user_id + postRandomName).updateChildren(postsMap).addOnCompleteListener(new OnCompleteListener() {
> >                         @Override
> public void onComplete(@NonNull Task task) {
> 
> if(task.isSuccessful())
> >                             {
> SendUserToMainActivity();
> Toast.makeText(PostActivity.this,"New Post is created successfully.",Toast.LENGTH_LONG).show();
> loadingBar.dismiss();
> >                             }
> else
> >                             {
> Toast.makeText(PostActivity.this,"Error occured while creating your post",Toast.LENGTH_LONG).show();
> loadingBar.dismiss();
> >                             }
> 
> >                         }
> >                     });
> 
> 
> 
> 
> >                 }
> 
> >             }
> 
> >             @Override
> public void onCancelled(@NonNull DatabaseError error) {
> 
> >             }
> >         });
> 
> >     }
> 
> private void OpenGallery() {
> 
> Intent galleryIntent = new Intent();
> galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
> galleryIntent.setType("image/*");
> startActivityForResult(galleryIntent,Gallery_Pick);
> 
> 
> >     }
> 
> 
> >     @Override
> protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
> 
> 
> super.onActivityResult(requestCode, resultCode, data);
> 
> if(requestCode == Gallery_Pick && resultCode == RESULT_OK && data!=null)
> >         {
> ImageUri = data.getData();
> SelectPostImage.setImageURI(ImageUri);
> >         }
> >     }
> 
> >     @Override
> public boolean onOptionsItemSelected(@NonNull MenuItem item) {
> 
> int id = item.getItemId();
> 
> if(id == androidx.appcompat.R.id.home)
> >         {
> SendUserToMainActivity();
> 
> >         }
> 
> return super.onOptionsItemSelected(item);
> >     }
> 
> >     @Override
> public boolean onSupportNavigateUp() {
> getOnBackPressedDispatcher().onBackPressed();
> return super.onSupportNavigateUp();
> >     }
> 
> private void SendUserToMainActivity() {
> 
> Intent mainIntent = new Intent(PostActivity.this, MainActivity.class);
> startActivity(mainIntent);
> 
> >     }
> > }
> 
> 
> 
> > ```
> 
> Here's the image of my Firebase database - 
> 
> 
> 
> [Here's The image of My Firebase Database, All other objects are getting stored but only  ` postsMap.put("postimage", downloadUrl);` not getting stored. ](https://i.stack.imgur.com/VqZCp.png)
> 
> 
> 
> Here's my xml code - 
> 
> 
> > ```
> > <?xml version="1.0" encoding="utf-8"?>
> > <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
> xmlns:app="http://schemas.android.com/apk/res-auto"
> xmlns:tools="http://schemas.android.com/tools"
> android:id="@+id/main"
> android:layout_width="match_parent"
> android:layout_height="match_parent"
> android:background="@drawable/login_register"
> tools:context=".PostActivity">
> 
> 
> >     <include
> android:id="@+id/update_post_page_toolbar"
> layout="@layout/app_bar_layout"
> 
> 
> 
> >         />
> 
> >     <ImageButton
> android:id="@+id/select_post_image"
> android:layout_width="match_parent"
> android:layout_height="300dp"
> android:layout_below="@id/update_post_page_toolbar"
> android:layout_alignParentStart="true"
> android:layout_margin="20dp"
> android:layout_marginTop="30dp"
> android:scaleType="fitCenter"
> app:srcCompat="@drawable/select_image" />
> 
> >     <EditText
> android:id="@+id/post_description"
> android:layout_width="match_parent"
> android:layout_height="wrap_content"
> android:layout_below="@id/select_post_image"
> android:layout_centerHorizontal="true"
> android:layout_margin="10dp"
> android:background="@drawable/inputs"
> android:ems="10"
> android:gravity="start|top"
> android:hint="write something about your image here"
> android:inputType="textMultiLine"
> android:padding="15dp"
> >         />
> 
> >     <Button
> android:id="@+id/update_post_button"
> android:layout_width="200dp"
> android:layout_height="wrap_content"
> android:layout_below="@id/post_description"
> android:layout_centerHorizontal="true"
> android:layout_margin="70dp"
> android:background="@drawable/button"
> android:padding="10dp"
> android:text="Create Post"
> android:textColor="@android:color/background_light"
> android:textSize="18sp" />
> 
> 
> > </RelativeLayout>
> 
> 
> > ```
> Here are my Gradle dependencies - 
> 
> dependencies {
> implementation(platform("com.google.firebase:firebase-bom:32.8.0"))
> implementation("com.google.firebase:firebase-database")
> implementation libs.appcompat
> implementation libs.material
> implementation libs.activity
> implementation libs.constraintlayout
> implementation libs.firebase.auth
> implementation libs.design
> testImplementation libs.junit
> androidTestImplementation libs.ext.junit
> androidTestImplementation libs.espresso.core
> 
> 
> implementation 'com.android.support:design:28.0.0'
> 
> implementation 'de.hdodenhof:circleimageview:3.1.0'
> 
> api 'com.theartofdev.edmodo:android-image-cropper:2.8.+'
> 
> implementation 'com.squareup.picasso:picasso:2.5.2'
> 
> implementation 'com.github.bumptech.glide:glide:4.16.0'
> 
> > }
> 
> 
> Post images are getting stored in Firebase Storage.
> 
> 
> 
> 
> 
> I think there's a problem with this block of code, but i can't figure out what is the excat problem, so please help..................
> 
> 
> > ````
> StorageReference filePath = PostsImagesReference.child("Post Images").child(ImageUri.getLastPathSegment() + postRandomName + ".jpg");
> 
> 
> 
> 
> filePath.putFile(ImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
> >                             @Override
> public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
> 
> 
> if(task.isSuccessful())
> >                                 {
> filePath.putFile(ImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
> >                                         @Override
> public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
> filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
> >                                                 @Override
> public void onSuccess(Uri uri) {
> downloadUrl =  uri.toString();
> 
> >                                                 }
> >                                             });
> >                                         }
> >                                     });
> 
> 
> Toast.makeText(PostActivity.this,"Image uploaded successfully to storage", Toast.LENGTH_LONG).show();
> 
> SavingPostInformationToDatabase();
> 
> >                                 }
> else
> >                                 {
> String message = task.getException().getMessage();
> Toast.makeText(PostActivity.this,"Error Occured: " + message, Toast.LENGTH_LONG).show();
> >                                 }
> 
> >                             }
> >                         });
> 
> 
> 
> 
> 
> >     }
> 
> > ```
> 
``
android firebase google-cloud-platform firebase-realtime-database firebase-storage
1个回答
0
投票

除了一个对象(即

postsMap.put("postimage", downloadUrl);
)之外,所有其他对象都被存储。此特定数据不会存储在 Firebase 实时数据库中。

发生这种情况是因为

downloadUrl
的值为空。与 Firestore 不同,在 Firestore 中,null 是受支持的数据类型,而在实时数据库中,您无法存储
null
值。一旦字段的值变为
null
,该节点将不再存在。因此,如果您在 Firebase 控制台中查找具有
null
值的字段,您将找不到它。

为什么

downloadUrl
为空?这是因为当您创建
postsMap
并添加
downloadUrl
时,值是
null
,因为在存储中添加文件的操作是异步的。因此,您应该等到上传文件的操作成功后,立即执行任何需要
downloadUrl
值的操作。

所以解决方案总是相同的。任何需要使用作为异步操作响应的数据的代码都需要位于

onSuccess
方法内部或从那里调用。

因此,如果您需要将数据添加到 Firebase 实时数据库,请在

onSuccess
方法中执行此操作,您 100% 确定会生成
downloadUrl
,并且可以使用它来将完整数据添加到数据库。

© www.soinside.com 2019 - 2024. All rights reserved.