简体   繁体   English

如何上传图像 Url 上传到 Fire Storage 并同时将其保存在 fireStore 使用 Java

[英]how to upload image Url Uploaded to Fire Storage and Save it in fireStore at the Same time Using Java

Here's my code where i can retrieve the image Url in Toast message where it is unable to save it in firestore please tell me if there is another method to do it or is the problem where i store the URL:这是我的代码,我可以在 Toast 消息中检索图像 Url,但它无法将其保存在 firestore 中,请告诉我是否有其他方法可以做到这一点,或者是我存储 URL 的问题:

public class register extends AppCompatActivity {

     EditText emails;
    EditText passwords;
    EditText ages;
    Button registers;
    Button addImage;
    EditText country;

    FirebaseFirestore db;
    FirebaseAuth auth;
    FirebaseUser auth1;
    private StorageTask task;

    Uri url ;
    Uri imageUri;

    static final int IMAGE_REQUEST =2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);


        auth = FirebaseAuth.getInstance();
        registers = findViewById(R.id.button);
        emails = findViewById(R.id.eamil);
        passwords = findViewById(R.id.password);
        ages=findViewById(R.id.age);
        country=findViewById(R.id.country);
        addImage = findViewById(R.id.button51);

         db =FirebaseFirestore.getInstance();





             registers.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String v_email = emails.getText().toString();
                String v_password = passwords.getText().toString();


                if (TextUtils.isEmpty(v_email)||TextUtils.isEmpty(v_password)){

                    Toast.makeText(register.this,"Eempty Credentials",Toast.LENGTH_SHORT).show();
                }else if(v_password.length()<6){

                    Toast.makeText(register.this,":password is short",Toast.LENGTH_SHORT).show();

                }else{









                        upload();
                        registerUser(v_email, v_password);




                }
            }
        });

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

                     openImage();

                 }
             });



    }

    private void registerUser(final String email, final String password) {

        auth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(register.this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {

                if(task.isSuccessful()){


                    Map<String , Object> users = new HashMap<>();
                    users.put("Email", emails.getText().toString());
                    users.put("Password", passwords.getText().toString());
                    users.put("Country", country.getText().toString());
                    users.put("AGe", ages.getText().toString());
                    users.put("Image", url.toString());
                    auth1 = FirebaseAuth.getInstance().getCurrentUser();
                    db.collection("Users").document(auth1.getUid()).set(users).addOnCompleteListener(new OnCompleteListener<Void>() {
                        @Override
                        public void onComplete(@NonNull Task<Void> task) {

                            //Toast.makeText(com.example.pleasework.register.this,"registeration was successful",Toast.LENGTH_SHORT).show();

                        }
                    });



//                    startActivity(new Intent(com.example.pleasework.register.this, MainActivity.class));
//                    finish();


                }else{


                    Toast.makeText(com.example.pleasework.register.this,"Resgisteration fail",Toast.LENGTH_SHORT).show();
                }
            }
        });


    }
    public  String getFileExtension(Uri uri){

        ContentResolver contentResolver = getContentResolver();
        MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();

        return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri));



    }

   public void  upload (){

        if (imageUri != null){


            final StorageReference fileRef  = FirebaseStorage.getInstance().getReference(System.currentTimeMillis()+getFileExtension(imageUri) );

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

                            fileRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                                @Override
                                public void onSuccess(Uri uri) {

                                    url = uri;
                                    Toast.makeText(register.this,"Upload Sucess" + url.toString(),Toast.LENGTH_SHORT).show();

                                }
                            });

                        }
                    });


        }


    }

    public  void openImage(){

        Intent intent = new Intent();
        intent.setType("image/");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent,IMAGE_REQUEST);

    }

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

    }
}




            }
        });
    }


}

and in fire store the field is always coming null but it is saved in the firestorage.在 fire store 中,字段总是出现 null 但它保存在 firestorage 中。

Wanted to add an image for FireStore but coludn't想为 FireStore 添加图像,但没有

Thanks.谢谢。

This process is called AsyncTask , which is intended to perform a process before a process.这个进程被称为AsyncTask ,它的目的是在一个进程之前执行一个进程。

It works to upload the image and the data at the same time, so the image link does not store because it did not finish uploading the image, and this is in less than a split of a second.它的工作原理是同时上传图片和数据,所以图片链接没有存储,因为它没有上传完图片,这在不到一秒钟的时间里。

You can use this method when the image is finished uploading, the data is stored in FireStore:当图片上传完成后,你可以使用这个方法,数据存储在 FireStore 中:

   private void registerUser(final String email, final String password) {

            auth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(register.this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {

                    if(task.isSuccessful()){
                       upload ();
                    }
});

Here be sure to upload the image first and then add ImageUrl to the fireStore:这里一定要先上传图片再将ImageUrl添加到fireStore:

public void  upload (){

        if (imageUri != null){


            final StorageReference fileRef  = FirebaseStorage.getInstance().getReference(System.currentTimeMillis()+getFileExtension(imageUri) );

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

                            fileRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                                @Override
                                public void onSuccess(Uri uri) {

                                    url = uri;

                                Map<String , Object> users = new HashMap<>();
                                users.put("Email", emails.getText().toString());
                                users.put("Password", passwords.getText().toString());
                                users.put("Country", country.getText().toString());
                                users.put("AGe", ages.getText().toString());
                                users.put("Image", url.toString());
                                auth1 = FirebaseAuth.getInstance().getCurrentUser();

                    db.collection("Users").document(auth1.getUid()).set(users).addOnCompleteListener(new OnCompleteListener<Void>() {
                        @Override
                        public void onComplete(@NonNull Task<Void> task) {

                             Toast.makeText(register.this,"Upload Sucess" + url.toString(),Toast.LENGTH_SHORT).show();

                             }
                         });

                       }
                   });
                }
            }); 
        }

    }

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

相关问题 如何从 firebase 存储中获取图像 URL 列表并将其上传到云 firestore? - How to get a list of image URL from firebase storage and upload it to cloud firestore? 使用 laravel 将图像上传到 Firestore - Upload image to firestore using laravel 如何使用 Admin SDK Java 将 PDF 文件上传到 Firebase 存储? - How to upload PDF file to Firebase Storage using Admin SDK Java? 如何使用 Java 中的 Firebase Admin 将文件上传到 Firebase 存储? - How to Upload file to Firebase Storage using Firebase Admin in Java? 图片已上传但未在 firebase 存储中接收。 控制台显示文件上传成功。 但不显示在存储中 - image uploaded but not receive in firebase storage. console show file upload successfully. but not show in storage 在 jsPDF 中插入 firestore 上传的图片 - Insert firestore uploaded image in jsPDF 如何获取上传的图片并将其存储在firebase存储中? - How to get an image uploaded and store it in the firebase storage? 如何等待firebase存储上传图片后再使用? - How to wait for firebase storage to upload image before using it? Android中如何使用Kotlin上传图片到Firebase存储 Q - How to upload an Image to Firebase Storage using Kotlin in Android Q 如何获取带有上传文件令牌的 url 到 firebase 存储? - How do I get url with token of uploaded file to firebase storage?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM