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

强颜欢笑 提交于 2021-01-06 03:29:42

问题


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:

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 .

Wanted to add an image for FireStore but coludn't

Thanks.


回答1:


This process is called AsyncTask, which is intended to perform a process before a process.

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 :

   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 :

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();

                             }
                         });

                       }
                   });
                }
            }); 
        }

    }


来源:https://stackoverflow.com/questions/61826518/how-to-upload-image-url-uploaded-to-fire-storage-and-save-it-in-firestore-at-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!