【问题标题】:How do I upload image, text, user id and timestamp to firebase firestore?如何将图像、文本、用户 ID 和时间戳上传到 Firebase Firestore?
【发布时间】:2020-10-28 20:28:08
【问题描述】:

我一直在尝试使用Map<>s 和HashMaps 将图像、用户 ID 时间戳和文本上传到 Firestore,但我不知道代码有什么问题。每次尝试时应用程序都会崩溃上传带文字的图片。

这是xml文件

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".NewPost">

<androidx.appcompat.widget.Toolbar
    android:id="@+id/new_post_toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:titleTextColor="@color/white"
    android:background="@color/colorPrimary"
    android:theme="@style/AppTheme_Toolbar"/>

<ProgressBar
    android:id="@+id/new_post_progressBar"
    android:layout_marginTop="5dp"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="20dp"
    android:orientation="vertical"
    android:gravity="center">

    <ImageView
        android:id="@+id/new_post_Image"
        android:layout_width="370dp"
        android:layout_height="300dp"
        android:background="@mipmap/insertphoto1"/>

    <EditText
        android:id="@+id/new_post_Desc"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:textSize="20sp"
        android:maxLength="130"
        android:fontFamily="@font/font2"
        android:hint="Write something..."/>

    <Button
        android:id="@+id/post_Btn"
        android:layout_marginTop="70dp"
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:background="@drawable/btn_background"
        android:text="Post"
        android:textSize="20sp"
        android:fontFamily="@font/font2"
        android:textAllCaps="false"
        android:textColor="@color/white"/>
</LinearLayout>

这是java文件

package com.example.vlog;


public class NewPost extends AppCompatActivity {

    private Toolbar newPostToolbar;

private ImageView newPostImage;
private EditText newPostDesc;
private  Button newPostBtn;
private  Uri postImageURI = null;

private ProgressBar newPostProgress;

private StorageReference storageReference;
private FirebaseFirestore firebaseFirestore;
private FirebaseAuth firebaseAuth;

private String current_user_id;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_new_post);

    newPostToolbar = findViewById(R.id.new_post_toolbar);
    setSupportActionBar(newPostToolbar);
    getSupportActionBar().setTitle("Add New Post");
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    firebaseFirestore = FirebaseFirestore.getInstance();
    storageReference = FirebaseStorage.getInstance().getReference();
    firebaseAuth = FirebaseAuth.getInstance();

    current_user_id = firebaseAuth.getCurrentUser().getUid();

    newPostImage = findViewById(R.id.new_post_Image);
    newPostDesc = findViewById(R.id.new_post_Desc);
    newPostBtn = findViewById(R.id.post_Btn);
    newPostProgress = findViewById(R.id.new_post_progressBar);

    newPostImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            CropImage.activity()
                    .setGuidelines(CropImageView.Guidelines.ON)
                    .setMinCropResultSize(512, 512)
                    .setAspectRatio(1,1)
                    .start(NewPost.this);
        }
    });

    newPostBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            final String desc = newPostDesc.getText().toString();

            if (!TextUtils.isEmpty(desc)  && postImageURI != null)
            {
                newPostProgress.setVisibility(View.VISIBLE);

                String randomName = FieldValue.serverTimestamp().toString();

                StorageReference filepath = storageReference
                        .child("post_images")
                        .child(randomName + ".jpg");

                filepath.putFile(postImageURI).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {

                        if (task.isSuccessful())
                        {
                            Task<Uri> download_Uri = task.getResult().getStorage().getDownloadUrl();

                            Map<String, Object> postMap = new HashMap<>();
                            postMap.put("image_url", download_Uri);
                            postMap.put("desc", desc);
                            postMap.put("user_id", current_user_id);
                            postMap.put("timestamp", FieldValue.serverTimestamp());

                            firebaseFirestore.collection("Posts")
                                    .add(postMap)
                                    .addOnCompleteListener(new OnCompleteListener<DocumentReference>() {
                                        @Override
                                        public void onComplete(@NonNull Task<DocumentReference> task) {

                                            if (task.isSuccessful())
                                            {
                                                Toast.makeText(NewPost.this,"Post uploaded..",Toast.LENGTH_LONG).show();
                                                Intent i = new Intent(NewPost.this, MainActivity.class);
                                                startActivity(i);
                                                finish();

                                            }else {
                                                String error = task.getException().getMessage();
                                                Toast.makeText(NewPost.this,"FIRESTORE Error : " + error,Toast.LENGTH_LONG).show();
                                            }

                                        }
                                    });

                        }
                        else {

                            newPostProgress.setVisibility(View.INVISIBLE);

                        }
                    }
                });
            }
        }
    });

}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
    {
        CropImage.ActivityResult result = CropImage.getActivityResult(data);
        if (resultCode == RESULT_OK) {

            postImageURI = result.getUri();
            newPostImage.setImageURI(postImageURI);

        } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
            Exception error = result.getError();
        }
    }
}

}

来自 Logcat 的堆栈跟踪错误

[1]:2020-07-09 00:54:34.969 24068-24068/com.example.vlog E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.vlog, PID: 24068 java.lang.RuntimeException: java.lang.reflect.InvocationTargetException at com.google.firebase.firestore.util.ApiUtil.invoke(com.google.firebase:firebase-firestore@@21.4.3:65) at com.google.firebase.firestore.util.CustomClassMapper$BeanMapper.serialize(com.google.firebase:firebase-firestore@@21.4.3:883) at com.google.firebase.firestore.util.CustomClassMapper.serialize(com.google.firebase:firebase-firestore@@21.4.3:178) at com.google.firebase.firestore.util.CustomClassMapper.serialize(com.google.firebase:firebase-firestore@@21.4.3:140) at com.google.firebase.firestore.util.CustomClassMapper.serialize(com.google.firebase:firebase-firestore@@21.4.3:104) at com.google.firebase.firestore.util.CustomClassMapper.convertToPlainJavaTypes(com.google.firebase:firebase-firestore@@21.4.3:78) at com.google.firebase.firestore.UserDataReader.convertAndParseDocumentData(com.google.firebase:firebase-firestore@@21.4.3:231) at com.google.firebase.firestore.UserDataReader.parseSetData(com.google.firebase:firebase-firestore@@21.4.3:75) at com.google.firebase.firestore.DocumentReference.set(com.google.firebase:firebase-firestore@@21.4.3:166) at com.google.firebase.firestore.DocumentReference.set(com.google.firebase:firebase-firestore@@21.4.3:146) at com.google.firebase.firestore.CollectionReference.add(com.google.firebase:firebase-firestore@@21.4.3:121) at com.example.vlog.NewPost$2$1.onComplete(NewPost.java:116) at com.google.firebase.storage.StorageTask.lambda$new$2(com.google.firebase:firebase-storage@@19.1.1:143)

【问题讨论】:

  • 如果应用程序崩溃,会有一个堆栈跟踪。请在 logcat 上查找,并将其添加到您的问题中。
  • 请将堆栈跟踪的屏幕截图替换为文本形式的实际(和完整)堆栈跟踪。

标签: java android firebase google-cloud-firestore firebase-storage


【解决方案1】:

您需要使用 firebase 存储来存储图像,他们将图像的 url 连同 id、名称和时间戳一起存储在 firestore 中。

检查这里.. https://firebase.google.com/docs/storage/?gclid=Cj0KCQjw3ZX4BRDmARIsAFYh7ZKX57WK_kP0vuxkxgrngT-U7xNalJ5Sj-paSGq0rVHM1Jd5RExfiRcaAopsEALw_wcB

【讨论】:

  • 我就是这么做的。 logcat 显示错误在 #116 行。这与我如何初始化 Map 和 HashMap 有关。但我不知道该怎么做
  • @Worldboss - 你检查过这个答案吗? stackoverflow.com/questions/51611632/…
  • 是的,我有,但在这种情况下如何使用哈希图。
【解决方案2】:
  1. 确保相应地设置存储规则 -> 如果您首先是身份验证用户,则使用 if request.auth != null;

或 -> 如果您不是首先验证用户,则使用 if request.auth == null;

  1. 改为使用uploadTask()。
StorageReference filepath = storageReference
                        .child("post_images")
                        .child(randomName + ".jpg");

uploadTask = filepath.putBytes(profile_byte);

uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
            
           
           uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
                    @Override
                    public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
                        if (!task.isSuccessful()) {
                            throw task.getException();
                        }

                        // Continue with the task to get the download URL
                        return filepath.getDownloadUrl();
                    }
                }).addOnCompleteListener(new OnCompleteListener<Uri>() {
                    @Override
                    public void onComplete(@NonNull Task<Uri> task) {
                        if (task.isSuccessful()) 
                           String downloadUri = task.getResult();

                            Map<String, Object> postMap = new HashMap<>();
                            postMap.put("image_url", downloadUri);
                            postMap.put("desc", desc);
                            postMap.put("user_id", current_user_id);
                            
                           postMap.put("timestamp",FieldValue.serverTimestamp());


                           db.collection("SavedDots").document(keyID).set(map, SetOptions.merge())
.addOnSuccessListener(new OnSuccessListener<Void>() {
                                            @Override
                                            public void onSuccess(Void aVoid) {}});
}
});


【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-04
    • 2019-06-28
    • 2020-07-27
    • 2018-08-13
    • 2019-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多