I want to save image url in real-time database but none of the solutions that I tried is solve the problem, the code that I wrote it saving the image in firebase storage but I want to save the image url in real-time database, so can anyone help?
this code just save the image in firebase storage
private Button btn_upload,btn_choose;
private ImageView imageView;
private Uri filepath;
private FirebaseStorage storage;
private StorageReference storageReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_choose= (Button) findViewById(R.id.btn_choose);
btn_upload= (Button) findViewById(R.id.btn_upload);
imageView= (ImageView) findViewById(R.id.myImage);
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
btn_upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uploadImage();
}
});
btn_choose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chooseImage();
}
});
}
// choose image function code
private void uploadImage() {
if(filepath!=null) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
StorageReference reference = storageReference.child("images/" + UUID.randomUUID().toString());
reference.putFile(filepath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Image uploaded", Toast.LENGTH_SHORT) .show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progres = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot.getTotalByteCount());
progressDialog.setMessage("Uploaded"+(int)progres+"%");
}
}) ;
} }
I want to store image in real-time database
You can request download URL for the file after uploading finishes.
Then Add the URL to Real-time Database
reference.putFile(filepath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Image uploaded", Toast.LENGTH_SHORT) .show();
reference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
//You will get donwload URL in uri
Log.d(TAG, "Download URL = "+ uri.toString());
//Adding that URL to Realtime database
mDatabase.child("imageUrl").setValue(uri.toString());
}
});
}
})
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null )
{
filePath = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
private void uploadImage() {
name = txtname.getText().toString();
if(filePath != null)
{
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
StorageReference ref = storageReference.child("images/"+ name);
ref.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Uploaded", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Failed "+e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot
.getTotalByteCount());
progressDialog.setMessage("Uploaded "+(int)progress+"%");
}
});
}
Toast.makeText(this, name, Toast.LENGTH_SHORT).show();
}
Related
I made a simple app that has a button and an ImageView. When I click on the button, an image (from drawable) gets displayed on the ImageView. I have also written the code for uploading the image on Firebase, but the exception message of onAddFailureListener gives the message User does not have permission to access this object. What should I do?
This answer does not help me.
User does not have permission to access this object . Firebase storage android
public class MainActivity extends AppCompatActivity {
private static final int PICK_IMAGE_REQUEST = 1;
private Button mButtonChooseImage;
private Button mButtonUpload;
private TextView mTextViewShowUploads;
private EditText mEditTextFileName;
private ImageView mImageView;
private ProgressBar mProgressBar;
private Uri mImageUri;
private StorageReference mStorageRef;
private DatabaseReference mDatabaseRef;
private StorageTask mUploadTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButtonChooseImage = findViewById(R.id.button_choose_image);
mButtonUpload = findViewById(R.id.button_upload);
mTextViewShowUploads = findViewById(R.id.text_view_show_uploads);
mEditTextFileName = findViewById(R.id.edit_text_file_name);
mImageView = findViewById(R.id.image_view);
mProgressBar = findViewById(R.id.progress_bar);
mStorageRef = FirebaseStorage.getInstance().getReference("uploads");
mDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads");
mButtonChooseImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
}
});
mButtonUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mUploadTask != null && mUploadTask.isInProgress()) {
Toast.makeText(MainActivity.this, "Upload in progress", Toast.LENGTH_SHORT).show();
} else {
uploadFile();
}
}
});
mTextViewShowUploads.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openImagesActivity();
}
});
}
private void openFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null) {
mImageUri = data.getData();
Picasso.get().load(mImageUri).into(mImageView);
}
}
private String getFileExtension(Uri uri) {
ContentResolver cR = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
private void uploadFile() {
if (mImageUri != null) {
StorageReference fileReference = mStorageRef.child(System.currentTimeMillis()
+ "." + getFileExtension(mImageUri));
mUploadTask = fileReference.putFile(mImageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mProgressBar.setProgress(0);
}
}, 500);
Toast.makeText(MainActivity.this, "Upload successful", Toast.LENGTH_LONG).show();
Upload upload = new Upload(mEditTextFileName.getText().toString().trim(),
/*
taskSnapshot.getMetadata().getReference().getDownloadUrl().toString());
String uploadId = mDatabaseRef.push().getKey();
mDatabaseRef.child(uploadId).setValue(upload);
*/
Objects.requireNonNull(taskSnapshot.getMetadata()).getReference().getDownloadUrl().toString());
String uploadId = mDatabaseRef.push().getKey();
assert uploadId != null;
mDatabaseRef.child(uploadId).setValue(upload);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
mProgressBar.setProgress((int) progress);
}
});
} else {
Toast.makeText(this, "No file selected", Toast.LENGTH_SHORT).show();
}
}
private void openImagesActivity() {
Intent intent = new Intent(this, ImagesActivity.class);
startActivity(intent);
}
}
Realtime Database
{
"rules": {
".read": true,
".write": true
}
}
Storage
rules_version = '2';
service firebase.storage {
match /b/savephoto-a1cc3.appspot.com/o {
match /{allPaths=**} {
// Allow access by all users
allow read, write;
}
}
}
Since I have seen a comment in your code that sounds like this "Allow access by all users", then I recommend you use the following rules:
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write;
}
}
}
For testing purposes, it will work but I encourage you to change them when you'll launch the application.
I'm new to android development and I have used firebase inside the project and tried all the ways to show the user profile picture inside the image view but none of the solutions works for me. Uploading profile image to firebase is working fine whenever I click on the save button the profile image and cover image uploaded successfully but it's not showing inside the imageview
public class Profile extends AppCompatActivity {
public static final int CAMERA_PERMISSION_CODE = 101;
public static final int CAMERA_REQUEST_CODE = 102;
public static final int PICK_IMAGE_REQUEST = 111;
private Uri uri;
private Uri coverUri;
EditText fullName, email, phone;
Button saveProfileBtn, logoutProfileBtn;
ImageView userProfileImage, userCoverImage;
ImageButton cameraBtn, userCoverBtn;
FirebaseStorage storage;
StorageReference storageReference;
FirebaseAuth fAuth;
FirebaseFirestore fStore;
FirebaseUser fUser;
String userID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ActionBar actionBar;
actionBar = getSupportActionBar();
ColorDrawable colorDrawable = new ColorDrawable(Color.parseColor("#3498DB"));
actionBar.setBackgroundDrawable(colorDrawable);
actionBar.setTitle(Html.fromHtml("<font color='#ffffff'>Profile Settings </font>"));
fullName = findViewById(R.id.userNameProfile);
email = findViewById(R.id.emailUserProfile);
phone = findViewById(R.id.phoneNoProfile);
saveProfileBtn = findViewById(R.id.saveBtnProfile);
logoutProfileBtn = findViewById(R.id.logoutBtn);
userProfileImage = findViewById(R.id.proImgProfile);
cameraBtn = findViewById(R.id.cameraBtnProfile);
userCoverImage = findViewById(R.id.coverPhotoPS);
userCoverBtn = findViewById(R.id.coverImageUpload);
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
fAuth = FirebaseAuth.getInstance();
fStore = FirebaseFirestore.getInstance();
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
cameraBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ImagePicker.with(Profile.this)
.crop() //Crop image(Optional), Check Customization for more option
.compress(512) //Final image size will be less than 1 MB(Optional)
.maxResultSize(512, 512) //Final image resolution will be less than
// 512 x 512(Optional)
.start(10);
// uploadImage();
}
});
userCoverBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ImagePicker.with(Profile.this)
.crop() //Crop image(Optional), Check Customization for more option
.compress(512) //Final image size will be less than 1 MB(Optional)
.maxResultSize(512, 512) //Final image resolution will be less than
// 512 x 512(Optional)
.start(20);
}
});
userID = fAuth.getCurrentUser().getUid();
DocumentReference documentReference = fStore.collection("users").document(userID);
documentReference.addSnapshotListener(this, new EventListener<DocumentSnapshot>() {
#Override
public void onEvent(#Nullable DocumentSnapshot value, #Nullable FirebaseFirestoreException error) {
fullName.setText(value.getString("fname"));
email.setText(value.getString("email"));
phone.setText(value.getString("phone"));
}
});
saveProfileBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
uploadImage(); //Calling function to upload profile image
coverUploadImage(); //Calling function to upload cover image
String fname = fullName.getText().toString();
String femail = email.getText().toString();
String fphone = phone.getText().toString();
if (TextUtils.isEmpty(fname)) {
fullName.setError("Please Enter Your Full Name");
return;
}
if (TextUtils.isEmpty(femail)) {
email.setError("Please Enter Your Email Address");
return;
}
if (fphone.length() < 10) {
phone.setError("Phone Number Shouble Be 10 Digit");
return;
}
if (TextUtils.isEmpty(fphone)) {
phone.setError("Please Enter Your Phone Number");
return;
}
DocumentReference documentReference =
FirebaseFirestore.getInstance().collection("users").document(userID);
Map<String, Object> user = new HashMap<>();
user.put("fname", fname);
user.put("email", femail);
user.put("phone", fphone);
documentReference.update(user).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
Toast.makeText(Profile.this, "Profile Updated Successfully", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Profile.this, "Failed to Update the Profile", Toast.LENGTH_SHORT).show();
}
});
}
});
logoutProfileBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(getApplicationContext(), login.class));
finish();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 10) {
uri = data.getData();
userProfileImage.setImageURI(uri);
}
if (requestCode == 20)
{
coverUri = data.getData();
userCoverImage.setImageURI(coverUri);
}
}
private void showUploadedImage() {
Uri uri = fUser.getPhotoUrl();
Glide.with(this).load(uri).into(userProfileImage);
}
// Function to upload profile image
private void uploadImage() {
if (uri != null) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading Profile Image");
progressDialog.show();
StorageReference ref = storageReference.child("userProfileImages/" + FirebaseAuth.getInstance().getCurrentUser().getUid());
ref.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(Profile.this, "Profile Picture Uploaded Successfully",
Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(Profile.this,
"Failed to Uploaded Profile Picture"+e.getMessage(), Toast.LENGTH_SHORT).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot snapshot) {
double progress = (100.0*snapshot.getBytesTransferred()/snapshot
.getTotalByteCount());
progressDialog.setMessage("Uploaded "+(int)progress+"%");
}
});
}
}
// Function to upload cover image
private void coverUploadImage() {
if (coverUri != null) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading Cover Picture");
progressDialog.show();
StorageReference ref =
storageReference.child("userCoverImages/" + FirebaseAuth.getInstance().getCurrentUser().getUid());
ref.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(Profile.this, "Cover Picture Uploaded Successfully",
Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(Profile.this,
"Failed to Upload Cover Picture"+e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot snapshot) {
double progress = (100.0*snapshot.getBytesTransferred()/snapshot
.getTotalByteCount());
progressDialog.setMessage("Uploaded "+(int)progress+"%");
}
});
}
}
public void saveDocument(View view) {
}
}
You are saying that the uploading is working successfully, so try another way to get the image URL from storage and put the link in the hashmap with the user's phone, name, and email after uploading the image.
So try this:
StorageReference ref = storageReference.child("userProfileImages/" + FirebaseAuth.getInstance().getCurrentUser().getUid());
// Use add on progress like this.
ref.putFile(uri).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot snapshot) {
}
}).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();
}
return ref.getDownloadUrl();
}
}).addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String photoUrl = uri.toString();
// This is the uri that you want to use after to put in the user's hashmap
Glide.with(MainActivity.this).load(photoUrl).into(userProfileImage);
}
});
I am trying to figure out what is wrong with my code and no data is uploaded in FirebaseDatabase. When I press the post button image url is getting in FirebaseStorage but the rest data does not appear in my database. Here is the code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_a_boat);
firebaseStorage = FirebaseStorage.getInstance();
storageReference = firebaseStorage.getReference();
Brand = findViewById(R.id.BrandOfProduct);
Name = findViewById(R.id.Name);
Categories = findViewById(R.id.Categories);
Description = findViewById(R.id.Description);
Price = findViewById(R.id.Price);
Quantity = findViewById(R.id.Quantity);
UploadProduct = findViewById(R.id.Update);
firebaseAuth = FirebaseAuth.getInstance();
databaseReference = firebaseDatabase.getInstance().getReference("ProductDetails");
try {
String userid = FirebaseAuth.getInstance().getCurrentUser().getUid();
dataa = firebaseDatabase.getInstance().getReference("User").child(userid);
dataa.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
UsersBs usersBs = snapshot.getValue(UsersBs.class);
Address = usersBs.getAddress();
ProductImage = (ImageButton) findViewById(R.id.ProductImage);
ProductImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onSelectImageclick(v);
}
});
UploadProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
brand = Brand.getText().toString().trim();
name = Name.getText().toString().trim();
categories = Categories.getSelectedItem().toString().trim();
description = Description.getText().toString().trim();
quantity = Quantity.getText().toString().trim();
price = Price.getText().toString().trim();
uploadImage();
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}catch (Exception e){
Log.e("Σφάλμα: ",e.getMessage());
}
}
private void uploadImage() {
if(imageUri != null){
final ProgressDialog progressDialog = new ProgressDialog(UploadAProduct.this);
progressDialog.setTitle("Σαλπάρισμα.....");
progressDialog.show();
RandomUID = UUID.randomUUID().toString();
reference = storageReference.child(RandomUID);
BusinessId = FirebaseAuth.getInstance().getCurrentUser().getUid();
reference.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
reference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
ProductDetails info = new ProductDetails(brand, name, categories, quantity, price, description, uri, RandomUID, BusinessId);
Toast.makeText(UploadAProduct.this, ""+info, Toast.LENGTH_SHORT).show();
firebaseDatabase.getInstance().getReference("ProductDetails")
//.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(RandomUID)
.setValue(info)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
progressDialog.dismiss();
Toast.makeText(UploadAProduct.this,"Έτοιμή για σαλπάρισμα!",Toast.LENGTH_SHORT).show();
}
});
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(UploadAProduct.this,e.getMessage(),Toast.LENGTH_SHORT).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot.getTotalByteCount());
progressDialog.setMessage("Σαλπάρισε "+(int) progress+"%");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setCancelable(true);
}
});
}
}
private void startCropImageActivity(Uri imageuri){
CropImage.activity(imageuri)
.setGuidelines(CropImageView.Guidelines.ON)
.setMultiTouchEnabled(true)
.start(this);
}
private void onSelectImageclick(View v){
CropImage.startPickImageActivity(this);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(cropImageUri !=null && grantResults.length>0 && grantResults[0]== PackageManager.PERMISSION_GRANTED){
startCropImageActivity(cropImageUri);
}else{
Toast.makeText(this,"Ακύρωση! Η άδεια δεν εγκρύθηκε!",Toast.LENGTH_SHORT).show();
}
}
#Override
#SuppressLint("NewApi")
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if(requestCode==CropImage.PICK_IMAGE_CHOOSER_REQUEST_CODE && resultCode== Activity.RESULT_OK){
imageUri = CropImage.getPickImageResultUri(this,data);
if(CropImage.isReadExternalStoragePermissionsRequired(this,imageUri)){
cropImageUri = imageUri;
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},0);
}else{
startCropImageActivity(imageUri);
}
}
if(requestCode==CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE){
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if(resultCode==RESULT_OK){
((ImageButton) findViewById(R.id.ProductImage)).setImageURI(result.getUri());
Toast.makeText(this,"Η εικόνα περικόπηκε με επιτυχία!",Toast.LENGTH_SHORT).show();
}else if(resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE){
Toast.makeText(this,"Αποτυχία περικοπής"+result.getError(),Toast.LENGTH_SHORT).show();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
Well, I checked whether there was a problem with my database rules but nothing seems wrong, both "read" and "write" are turned "true". I also tried to delete my Firebase project and create a new one but the same problem was still there.
I'm trying to upload some images to firestore storage and put the image URL to firebase database. The images are uploading successfully but the image URLs aren't being added to the database. The problem that I think might be causing this is that the image URL is being added to the Hashmap after uploading the image but the database upload process isn't waiting for the URL instead, adding all other HashMap keys to the database before the Upload task returns the URL. This way all other keys get added to the database but not the Image URLs. In the below code product id is being added successfully to the database, also if I leave any image unselected its url alse gets added as empty to the database which is working fine but if I select an image to upload, The hashmap to database upload finishes even before getting the uploaded image URL.
public class AddProductDataActivity extends AppCompatActivity {
String productId;
EditText productIdEditText;
ImageView addProductImage3;
Button addProductSubmit;
final int IMAGE3_REQUEST = 30;
Uri image3LocationPath;
StorageReference objectStorageReference;
FirebaseFirestore objectFireBaseFireStore;
Map<String, String> objectMap = new HashMap<>();
StorageReference img3Store;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_product_data);
brandNameEditText =(EditText)
addProductImage3 = (ImageView) findViewById(R.id.add_product_image3);
objectStorageReference =
FirebaseStorage.getInstance().getReference("images");
objectFireBaseFireStore = FirebaseFirestore.getInstance();
addProductImage3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent objectIntent = new Intent();
objectIntent.setType("image/*");
objectIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(objectIntent, IMAGE3_REQUEST);
}
});
addProductSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
productId = productIdEditText.getText().toString();
if(image3LocationPath != null)
{
final String image3Name = productId + "_image3." + getExtension(image3LocationPath);
img3Store = objectStorageReference.child(image3Name);
UploadTask imageUploadTask = img3Store.putFile(image3LocationPath);
imageUploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if(!task.isSuccessful())
{
Toast.makeText(AddProductDataActivity.this, "Task Unsuccessful", Toast.LENGTH_SHORT).show();
}
return img3Store.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if(task.isSuccessful())
{
String image_3_url = task.getResult().toString();
objectMap.put("image3_url",image_3_url);
}
else
{
Toast.makeText(AddProductDataActivity.this, task.getException().toString(), Toast.LENGTH_SHORT).show();
}
}
});
}
else
{
objectMap.put("image3_url","");
}
objectFireBaseFireStore.collection("images").document(productId).set(objectMap).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(AddProductDataActivity.this, "Product Added Successfully.", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(AddProductDataActivity.this, "Error in Adding Product. Please Try Again.\n"+e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case 30:
try
{
if(resultCode == RESULT_OK && data != null && data.getData() != null)
{
image3LocationPath = data.getData();
Bitmap objectBitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), image3LocationPath);
addProductImage3.setImageBitmap(objectBitmap);
}
}
catch (Exception e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
break;
default:
break;
}
private String getExtension(Uri uri){
try
{
ContentResolver objectContentResolver = getContentResolver();
MimeTypeMap objectMimeTypeMap = MimeTypeMap.getSingleton();
return objectMimeTypeMap.getExtensionFromMimeType(objectContentResolver.getType(uri));
}
catch (Exception e)
{
Toast.makeText(AddProductDataActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
return null;
}
}
}
Your code
objectFireBaseFireStore.collection("images").document(productId).set(objectMap)
executes before
objectMap.put("image3_url",image_3_url)
Which means when you are setting your url, your objectMap does not have the key image3_url
Try to set values to database inside onComplete() or use different workaround to set only the url.
You forgot to add your HashMap to Database Reference of Firebase.
This is reference from my current project code.
private void uploadVideo() {
StorageReference mStorageRef = FirebaseStorage.getInstance().getReference();
final StorageReference riversRef = mStorageRef.child(Constants.STORAGE_PATH + "/" + mFinalUploadUri.getLastPathSegment());
riversRef.putFile(mFinalUploadUri).continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
throw Objects.requireNonNull(task.getException());
}
// Continue with the task to get the download URL
return riversRef.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
FirebaseFirestore database = FirebaseFirestore.getInstance();
String mSelectedCategory = binding.categorySpinner.getSelectedItem().toString();
DocumentReference newDocumentReference = database.collection(PENDING_PATH).document();
VideoModel videoModel = new VideoModel();
videoModel.setDocumentId(newDocumentReference.getId());
videoModel.setTitle(mTitle);
videoModel.setCategory(mSelectedCategory);
//videoModel.setTime(FieldValue.serverTimestamp());
videoModel.setUrl(downloadUri != null ? downloadUri.toString() : null);
newDocumentReference.set(videoModel).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
binding.progressBar.setVisibility(View.GONE);
binding.button.setVisibility(View.VISIBLE);
binding.videoView.setVisibility(View.GONE);
selectedUri = null;
Toast.makeText(AdminVideoUploadActivity.this, R.string.uploaded_successfully, Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(AdminVideoUploadActivity.this, R.string.failed_to_upload, Toast.LENGTH_SHORT).show();
}
});
}
}
});
}
Now you can check code and find where you have done mistake. Just add lines of code of inserting in database.
Thank you.
I have created a profile for my app. I want the user to be able to select an image from stored images on phone which then also updates profile pic into firebase. I am able to change to the profile pic and place into imageView, however when i close profile and then return the image has not saved onto the profile but uploaded to firebase.
Code for updating profile pic:
private void showImageChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Profile Image"), CHOOSE_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CHOOSE_IMAGE && resultCode == RESULT_OK && data != null && data.getData() != null) {
uriProfileImage = data.getData();
//try {
//Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uriProfileImage);
//imageView.setImageBitmap(bitmap);
Glide.with(this)
.load(uriProfileImage)
.apply(new RequestOptions()
.placeholder(R.drawable.icon_camera))
.into(imageView);
uploadImageToFirebaseStorage();
//} catch (IOException e) {
// e.printStackTrace();
}
}
private void uploadImageToFirebaseStorage() {
StorageReference profileImageRef =
FirebaseStorage.getInstance().getReference("profilepics/" + System.currentTimeMillis() + ".jpg");
if (uriProfileImage != null) {
progressBar.setVisibility(View.VISIBLE);
profileImageRef.putFile(uriProfileImage)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressBar.setVisibility(View.GONE);
profileImageUrl = taskSnapshot.getMetadata().getReference().getDownloadUrl().toString();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressBar.setVisibility(View.GONE);
Toast.makeText(ProfileActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
Upload user information:
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showImageChooser();
}
});
loadUserInformation();
findViewById(R.id.buttonSave).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveUserInformation();
}
});
Load user information
private void loadUserInformation() {
final FirebaseUser user = mAuth.getCurrentUser();
if (user != null) {
if (user.getPhotoUrl() != null) {
Glide.with(this)
.load(user.getPhotoUrl().toString())
.into(imageView);
}
if (user.getDisplayName() != null) {
editText.setText(user.getDisplayName());
}
if (user.isEmailVerified()) {
textView.setText("Email Verified");
} else {
textView.setText("Email Not Verified (Click to Verify)");
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
user.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(ProfileActivity.this, "Verification Email Sent", Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
}