图片存储到文件中而不是链接

时间:2018-07-18 11:50:09

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

我在Firebase存储中遇到问题。我制作一个项目,拍摄照片没有错误,并将其存储在Firestore中。问题在于手机路径中的url图片没有上传到Firebase存储中。突然,几天后,该图像甚至没有上传到Firebase存储中。当我看到Firestore时,它显示的图像链接来自手机存储。谁能帮我这个?

我已经编辑了我的代码..但仅将其发送到了Firestore ..出现了错误处理程序。

package my.wedee.com.wedeeon9bisnis;


                import android.Manifest;
                import android.content.Context;
                import android.content.Intent;
                import android.content.pm.PackageManager;
                import android.net.Uri;
                import android.os.Build;
                import android.support.annotation.NonNull;
                import android.support.v4.app.ActivityCompat;
                import android.support.v4.content.ContextCompat;
                import android.support.v7.app.AppCompatActivity;
                import android.os.Bundle;
                import android.support.v7.widget.Toolbar;
                import android.text.TextUtils;
                import android.view.MenuItem;
                import android.view.MotionEvent;
                import android.view.View;
                import android.view.inputmethod.InputMethodManager;
                import android.widget.Button;
                import android.widget.EditText;
                import android.widget.ProgressBar;
                import android.widget.Toast;

                import com.bumptech.glide.Glide;
                import com.bumptech.glide.request.RequestOptions;
                import com.google.android.gms.tasks.OnCompleteListener;
                import com.google.android.gms.tasks.OnFailureListener;
                import com.google.android.gms.tasks.Task;
                import com.google.firebase.auth.FirebaseAuth;
                import com.google.firebase.firestore.DocumentSnapshot;
                import com.google.firebase.firestore.FirebaseFirestore;
                import com.google.firebase.storage.FirebaseStorage;
                import com.google.firebase.storage.StorageReference;
                import com.theartofdev.edmodo.cropper.CropImage;
                import com.theartofdev.edmodo.cropper.CropImageView;

                import java.util.HashMap;
                import java.util.Map;

                import de.hdodenhof.circleimageview.CircleImageView;

                public class EditProfileActivity extends AppCompatActivity {


                    private EditText fullNameOwner, emailBiz, locationBiz;
                    private CircleImageView profileImage;
                    private Button SaveInformation;
                    private ProgressBar progressBar;

                    private Uri mainImageURI = null;

                    private FirebaseAuth mAuth;
                    private StorageReference storageReference;
                    private FirebaseFirestore mFireStore;

                    private String currentUserId;

                    private Boolean isChanged = false;
                    private Uri download_uri;

                    @Override
                    protected void onCreate(Bundle savedInstanceState) {
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.activity_edit_profile);


                        //firebase
                        mAuth = FirebaseAuth.getInstance();
                        mFireStore = FirebaseFirestore.getInstance();
                        storageReference = FirebaseStorage.getInstance().getReference();


                        currentUserId = mAuth.getCurrentUser().getUid();
                        progressBar = findViewById(R.id.progressBarEditProfile);

                        //toolbar
                        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbarEditInfo); // get the reference of Toolbar
                        toolbar.setTitle("Account Personal Info"); // set Title for Toolbar
                        setSupportActionBar(toolbar); // Setting/replace toolbar as the ActionBar

                        // add back arrow to toolbar
                        if (getSupportActionBar() != null) {
                            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
                            getSupportActionBar().setDisplayShowHomeEnabled(true);
                        }


                        //findviewbyID
                        fullNameOwner = findViewById(R.id.editTextFullnameBiz);
                        emailBiz = findViewById(R.id.editTextEmailBiz);
                        locationBiz = findViewById(R.id.editTextLocationBiz);
                        profileImage = findViewById(R.id.profile_image_edit);
                        SaveInformation = findViewById(R.id.buttonSaveInfoEdit);


                        progressBar.setVisibility(View.VISIBLE);
                        mFireStore.collection("Profile On9Biz").document(currentUserId).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {

                            @Override
                            public void onComplete(@NonNull Task<DocumentSnapshot> task) {

                                if (task.isSuccessful()) {

                                    if (task.getResult().exists()) {

                                        String fullname = task.getResult().getString("fullname");
                                        String email = task.getResult().getString("email");
                                        String location = task.getResult().getString("location");
                                        String image = task.getResult().getString("profile_images");

                                        mainImageURI = Uri.parse(image);


                                        fullNameOwner.setText(fullname);
                                        emailBiz.setText(email);
                                        locationBiz.setText(location);

                                        RequestOptions placeholderRequest = new RequestOptions();
                                        placeholderRequest.placeholder(R.drawable.profile);

                                        Glide.with(EditProfileActivity.this).setDefaultRequestOptions(placeholderRequest).load(image).into(profileImage);

                                        progressBar.setVisibility(View.INVISIBLE);

                                    }


                                } else {


                                    String errorMsg = task.getException().getMessage();
                                    Toast.makeText(EditProfileActivity.this, "Firebase Error :" + errorMsg, Toast.LENGTH_LONG).show();
                                }


                            }
                        });


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

                                progressBar.setVisibility(View.VISIBLE);

                                final String full_nameBiz = fullNameOwner.getText().toString().trim();
                                final String email_Ob = emailBiz.getText().toString().trim();
                                final String location_Ob = locationBiz.getText().toString().trim();


                                if (!TextUtils.isEmpty(full_nameBiz) && !TextUtils.isEmpty(email_Ob) && !TextUtils.isEmpty(location_Ob) && mainImageURI != null) {


                                    StorageReference image_path = storageReference.child("profile_images").child(currentUserId + ".jpg");
                                    image_path.putFile(mainImageURI);
                                    storageReference.getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
                                        @Override
                                        public void onComplete(@NonNull Task<Uri> task) {
                                            if (task.isSuccessful()) {

                                                download_uri = task.getResult();

                                                StoreFireStore(task,full_nameBiz,email_Ob,location_Ob);

                                            } else {

                                                String errorMsg = task.getException().getMessage();
                                                Toast.makeText(EditProfileActivity.this, "Internet Connection Error :" + errorMsg, Toast.LENGTH_LONG).show();
                                            }
                                        }
                                    }).addOnFailureListener(new OnFailureListener() {
                                        @Override
                                        public void onFailure(@NonNull Exception e) {


                                            Toast.makeText(EditProfileActivity.this, "Failed", Toast.LENGTH_SHORT).show();

                                        }
                                    });
                                    progressBar.setVisibility(View.INVISIBLE);

                                }

                            }
                        });


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


                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

                                    if (ContextCompat.checkSelfPermission(EditProfileActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

                                        Toast.makeText(EditProfileActivity.this, "Permission Denied...", Toast.LENGTH_SHORT).show();
                                        ActivityCompat.requestPermissions(EditProfileActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);

                                    } else {

                                        BringImagePicker();


                                    }

                                } else {

                                    BringImagePicker();


                                }

                            }
                        });


                    }

                    private void StoreFireStore(@NonNull Task<Uri> task, String full_nameBiz, String email_Ob, String location_Ob) {

                        Map<String, String> userMap = new HashMap<>();
                        userMap.put("fullname", full_nameBiz);
                        userMap.put("email", email_Ob);
                        userMap.put("location", location_Ob);
                        userMap.put("profile_images", download_uri.toString());

                        mFireStore.collection("Profile On9Biz").document(currentUserId).set(userMap).addOnCompleteListener(new OnCompleteListener<Void>() {
                            @Override
                            public void onComplete(@NonNull Task<Void> task) {

                                if (task.isSuccessful()) {


                                    Toast.makeText(EditProfileActivity.this, "Data Has Been Stored..", Toast.LENGTH_LONG).show();

                                    SentToProfile();

                                } else {

                                    String errorMsg = task.getException().getMessage();
                                    Toast.makeText(EditProfileActivity.this, "Firebase Error :" + errorMsg, Toast.LENGTH_LONG).show();


                                }

                                progressBar.setVisibility(View.VISIBLE);

                            }

                        });



                    }


                    private void SentToProfile() {


                        Intent nextIntent = new Intent(EditProfileActivity.this, ProfileActivity.class);
                        nextIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        startActivity(nextIntent);
                    }


                    @Override
                    protected void onActivityResult(int requestCode, int resultCode, 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) {

                                mainImageURI = result.getUri();
                                profileImage.setImageURI(mainImageURI);


                            } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {

                                Exception error = result.getError();
                                Toast.makeText(this, "Error :" + error, Toast.LENGTH_SHORT).show();


                            }
                        }

                    }


                    //hidekeyboard
                    @Override
                    public boolean onTouchEvent(MotionEvent event) {
                        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
                        return true;
                    }


                    //backButton
                    @Override
                    public boolean onOptionsItemSelected(MenuItem item) {
                        // handle arrow click here
                        if (item.getItemId() == android.R.id.home) {
                            SentToProfile(); // close this activity and return to preview activity (if there is any)
                        }

                        return super.onOptionsItemSelected(item);
                    }


                    private void BringImagePicker() {


                        CropImage.activity()
                                .setGuidelines(CropImageView.Guidelines.ON)
                                .setAspectRatio(1, 1)
                                .start(EditProfileActivity.this);


                    }
                }

See that image its show the link in firestore from the image i cropped, tell me how can i fix this

这是我的firebase存储规则...

        service firebase.storage {
      match /b/{bucket}/o {
        match /{allPaths=**} {
          allow read, write: if request.auth != null;
        }
      }
    }

这是我的Firestore规则:-

    service cloud.firestore {
   match /databases/{database}/documents {
     match /{document=**} {
     allow read, write: if request.auth != null;
   }
   }
 }

2 个答案:

答案 0 :(得分:1)

要确定图像的下载URL,请执行以下操作:

download_uri = storageReference.getDownloadUrl().getResult();

不幸的是,这可能无法正常工作,因为下载URL可能尚不可用。如果您查看documentation for StorageReference.getDownloadUrl(),它会显示:

  

public Task<Uri> getDownloadUrl ()

     

异步检索具有可撤消令牌的长期下载URL。

因此您没有获得URL,而是获得了一个Task,该异步返回URL。要获取实际的URL,您需要在任务上附加一个完成侦听器:

storageReference.getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
    @Override
    public void onComplete(@NonNull Task<Uri> task) {
        if (task.isSuccessful()) {
            download_uri = task.getResult();
            // TODO: write the download_uri to the database here
        }
    }

有关更长的示例,请参见Firebase Storage documentation on getting the download URL

答案 1 :(得分:0)

尝试一下:

String reviewPost = editReview.getText().toString().trim();
String userName = Objects.requireNonNull(FirebaseAuth.getInstance().getCurrentUser()).getDisplayName();
Uri profileImage = FirebaseAuth.getInstance().getCurrentUser().getPhotoUrl();

//Log.e("Image", "User Image" + userImage);
            String uId = FirebaseAuth.getInstance().getCurrentUser().getUid();
bookReviewUser = new HashMap<>();
bookReviewUser.put("ReviewId",uId);
bookReviewUser.put("ReviewPost",reviewPost);
bookReviewUser.put("UserName",username);
bookReviewUser.put("UserImage",profileImage.toString());
bookReviewUser.put("Date",new Timestamp(new Date()));
FirebaseFirestore.getInstance().collection("Review").document(userName)
                    .set(bookReviewUser)
                    .addOnSuccessListener(new OnSuccessListener<Void>() {
                        @Override
                        public void onSuccess(Void aVoid) {
                            hideProgressDialog();
                        }
                    });
};