Reputation: 33
i got problem in firebase storage. I make a project there is no error with take picture and store it in firestore. The problem is that url image from phone path and not uploaded into firebase storage.Before this, its works and uploaded into firebase. Suddenly, few days later, the image not even uploaded into firebase storage. When i see the firestore, its show the link of image was from phone storage. Can anyone Help me with this?
Im already edit my code.. but only sending it to firestore.. the error handler appear.
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);
}
}
Here is my firebase Storage rules...
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if request.auth != null;
}
}
}
and here is my Firestore Rules :-
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth != null;
}
}
}
Upvotes: 0
Views: 676
Reputation: 31
Give this a try:
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();
}
});
};
Upvotes: 0
Reputation: 598668
To determine the download URL for the image you do:
download_uri = storageReference.getDownloadUrl().getResult();
Unfortunately that may not work, since the download URL may not be available yet. If you look at the documentation for StorageReference.getDownloadUrl()
it says:
public Task<Uri> getDownloadUrl ()
Asynchronously retrieves a long lived download URL with a revokable token.
So you're not getting a URL, but a Task
that asynchronously returns the URL. To get the actual URL, you need to attach a completion listener to the task:
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
}
}
For a longer example, see the Firebase Storage documentation on getting the download URL.
Upvotes: 1