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();
}
});
}
});
}
}
}
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 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();
}
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.
Upload succeeded if imageUri was in this form.
content://com.android.providers.media.documents/document/image%3A12305
But this form failed
/document/image:10674
And I got this Toast message.
"An unknown error occurred, please check the HTTP result code and inner exception for server response."
I'd appreciate it if you could give me any hints.
What I tried
1.Get Image from gallery
Uri imageUri;
StorageTask uploadTask;
StorageReference storageReference;
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
File compressedImageFile; //for compress library : https://github.com/zetbaitsu/Compressor
if (requestCode == IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null) {
Uri selectedImageUri = data.getData();
try {
compressedImageFile = new Compressor(getContext()).compressToFile(new File(selectedImageUri.getPath()));
imageUri = data.getData(); //this works well but uploaded original size.
// imageUri =Uri.fromFile(compressedImageFile); //fail
// imageUri= Uri.fromFile(new File(compressedImageFile.toURI().getPath())); //fail
// imageUri= Uri.parse(new File(compressedImageFile.getPath()).toString()); //fail
if (uploadTask != null && uploadTask.isInProgress()) {
Toast.makeText(getContext(), "Upload in preogress", Toast.LENGTH_SHORT).show();
} else {
uploadImage();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.uploadImage();
if (imageUri != null) {
final StorageReference fileReference = storageReference.child(System.currentTimeMillis()
+ "." + getFileExtension(imageUri));
uploadTask = fileReference.putFile(imageUri);
uploadTask.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 fileReference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
String mUri = downloadUri.toString();
reference = FirebaseDatabase.getInstance().getReference("Users").child(fuser.getUid());
HashMap<String, Object> map = new HashMap<>();
map.put("imageURL", "" + mUri);
reference.updateChildren(map);
} else {
Toast.makeText(getContext(), "Failed!", Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
По пробуйте это
StorageReference riversRef =
storageRef.child("images/"+imageUri.getLastPathSegment());
uploadTask = riversRef.putFile(imageUri);
// Register observers to listen for when the download is done or if it
//fails
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// taskSnapshot.getMetadata() contains file metadata such as size,
//content-type, etc.
}
});
add this code into your file :-
StorageReference storageReference;
storageReference = storage.getReference();
final StorageReference ref = storageReference.child("images/" + UUID.randomUUID());
ref.putFile(your file path)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot> () {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
ref.getDownloadUrl().addOnSuccessListener(new
OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri imageUrl{
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(IndivudualChatActivity.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());
}
});
I want to add two different photos to the database via Android app. however, when I select a photo for the first photo, it places the same photo for both and saves it in the same way. My code's down there. I've defined two separate imageview for two different photos, but it doesn't work. What can I do?
mDenemeImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 1);
}
});
mDenemeImage2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK);
i.setType("image/*");
startActivityForResult(i, 1);
}
});
private void getUserInfo(){
mDriverDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists() && dataSnapshot.getChildrenCount()>0){
Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();
if(map.get("profileDenemeUrl")!=null){
mprofileDenemeUrl = map.get("profileDenemeUrl").toString();
Glide.with(getApplication()).load(mprofileDenemeUrl).into(mDenemeImage);
}
if(map.get("profileDenemeUrl2")!=null){
mprofileDenemeUrl2 = map.get("profileDenemeUrl2").toString();
Glide.with(getApplication()).load(mprofileDenemeUrl2).into(mDenemeImage2);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void saveUserInformation() {
Map userInfo = new HashMap();
mDriverDatabase.updateChildren(userInfo);
if(resultUri != null) {
final StorageReference filePath = FirebaseStorage.getInstance().getReference().child("profile_arac").child(userID);
final StorageReference filePath2 = FirebaseStorage.getInstance().getReference().child("profile_arac2").child(userID);
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(getApplication().getContentResolver(), resultUri);
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
byte[] data = baos.toByteArray();
UploadTask uploadTask = filePath.putBytes(data);
UploadTask uploadTask2 = filePath2.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
finish();
return;
}
});
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Map newImage = new HashMap();
newImage.put("profileDenemeUrl", uri.toString());
mDriverDatabase.updateChildren(newImage);
finish();
return;
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
finish();
return;
}
});
}
}); uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
finish();
return;
}
});
uploadTask2.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
filePath2.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Map newImage2 = new HashMap();
newImage2.put("profileDenemeUrl2", uri.toString());
mDriverDatabase.updateChildren(newImage2);
finish();
return;
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
finish();
return;
}
});
}
}); uploadTask2.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
finish();
return;
}
});
}
else{
finish();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && resultCode == Activity.RESULT_OK){
final Uri imageUri = data.getData();
resultUri = imageUri;
mDenemeImage.setImageURI(resultUri);
mDenemeImage2.setImageURI(resultUri);
}
}
mDenemeImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 1);
}
});
mDenemeImage2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK);
intent.setType("image/*"); startActivityForResult(i, 2);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && resultCode == RESULT_OK){
Uri imageUri1 = data.getData();
resultUri1 = imageUri1;
mDenemeImage.setImageURI(resultUri1);
}
if (requestCode == 2 && resultCode == RESULT_OK)
{
Uri imageUri2 = data.getData();
resultUri2 = imageUri2;
mDenemeImage2.setImageURI(resultUri2);
}
}