Store Multiple pictures in Firebase Storage - java

I have a code for storing images in the firebase storage but it only storing one image at a time and I need to Store multiple images
Here's the code:
Save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Saveimages();
}
});
}
private void Saveimages() {
comment = Comment.getText().toString();
if (imageUri==null||imageUri2==null){
Toast.makeText(this, "...Select a Image...", Toast.LENGTH_SHORT).show();
}
else if(imageUri!=null&&imageUri2!=null&&imageUri3==null&&imageUri4==null) {
Save2ImagesFirebase();
}
else if(imageUri!=null&&imageUri2!=null&&imageUri3!=null&&imageUri4==null){
Save3ImagesFirebase();
}
else if(imageUri!=null&&imageUri2!=null&&imageUri3!=null&&imageUri4!=null){
Save4ImagesFirebase();
}
}
private void Save2ImagesFirebase() {
StorageReference filepath = mStorage.child(" Images");
filepath.putFile(imageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()){
Toast.makeText(ImageVersus.this, " Published", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(ImageVersus.this, "..Error..", Toast.LENGTH_SHORT).show();
}
}
});
StorageReference filepath2 = mStorage.child(" Images");
filepath2.putFile(imageUri2).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()){
Toast.makeText(ImageVersus.this, " Published", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(ImageVersus.this, "..Error..", Toast.LENGTH_SHORT).show();
}
}
});
}
private void Save3ImagesFirebase() {
StorageReference filepath = mStorage.child(" Images");
filepath.putFile(imageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()){
Toast.makeText(ImageVersus.this, " Published", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(ImageVersus.this, "..Error..", Toast.LENGTH_SHORT).show();
}
}
});
StorageReference filepath2 = mStorage.child(" Images");
filepath2.putFile(imageUri2).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()){
Toast.makeText(ImageVersus.this, " Published", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(ImageVersus.this, "..Error..", Toast.LENGTH_SHORT).show();
}
}
});
StorageReference filepath3 = mStorage.child(" Images");
filepath3.putFile(imageUri3).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()){
Toast.makeText(ImageVersus.this, " Published", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(ImageVersus.this, "..Error..", Toast.LENGTH_SHORT).show();
}
}
});
}
private void Save4ImagesFirebase() {
StorageReference filepath = mStorage.child(" Images");
filepath.putFile(imageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()){
Toast.makeText(ImageVersus.this, " Published", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(ImageVersus.this, "..Error..", Toast.LENGTH_SHORT).show();
}
}
});
StorageReference filepath2 = mStorage.child(" Images");
filepath2.putFile(imageUri2).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()){
Toast.makeText(ImageVersus.this, " Published", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(ImageVersus.this, "..Error..", Toast.LENGTH_SHORT).show();
}
}
});
StorageReference filepath3 = mStorage.child(" Images");
filepath3.putFile(imageUri3).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()){
Toast.makeText(ImageVersus.this, " Published", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(ImageVersus.this, "..Error..", Toast.LENGTH_SHORT).show();
}
}
});
StorageReference filepath4 = mStorage.child(" Images");
filepath4.putFile(imageUri4).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()){
Toast.makeText(ImageVersus.this, " Published", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(ImageVersus.this, "..Error..", Toast.LENGTH_SHORT).show();
}
}
});
}
The code look long but is only much of the same. I try repeating the method depending on what the user do if he select only two images it should save those two at once and if he select tree it should save those 3 and so on...

Did you see that your code is actually duplicated?
Wrap your code in a function like this:
public void storeImage(Uri imageUri) {
StorageReference filepath = mStorage.child(" Images");
filepath.putFile(imageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()){
Toast.makeText(ImageVersus.this, " Published", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(ImageVersus.this, "..Error..", Toast.LENGTH_SHORT).show();
}
}
});
}
Now use can use it directly:
storeImage(imageUri);
or make use of multiple store:
public void storeMultipleImages(List<Uri> imageUris) {
for (Uri uri : imageUris) {
storeImage(uri);
}
}
There you can store any number of images with the code

Related

implementing addOnProgressListener In Firebase

In my code i want to add OnProgressListener, but can't work. It gives me a syntax error.
Cannot resolve method 'addOnProgressListener' in 'Task'
How i can do this?
Please rewrite the code for me.
I Want to show progress dialog percentage.
For example: "uploading video 98%"
private void uploadImage_10() {
final ProgressDialog pd = new ProgressDialog(this);
pd.setMessage("Posting....");
pd.show();
if (video_url != null) {
final StorageReference fileReference = storageRef.child(System.currentTimeMillis()
+ "." + getFileExtension(video_url));
uploadTask = fileReference.putFile(video_url);
String desc = description.getText().toString();
if (desc.length() < 20) {
description.setError("Please Insert Document to long");
if (TextUtils.isEmpty(desc)) {
description.setError("Please insert Description");
Toast.makeText(this, "Please Insert Description", Toast.LENGTH_SHORT).show();
}
pd.dismiss();
} else {
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();
miUrlOk = downloadUri.toString();
DatabaseReference reference = FirebaseDatabase.getInstance("https://pineka-social-media-mast-da52a-default-rtdb.firebaseio.com/"
).getReference("Posts_video");
String postid = reference.push().getKey();
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("postid", postid);
hashMap.put("time_post", ServerValue.TIMESTAMP);
hashMap.put("postvideo", miUrlOk);
hashMap.put("description", description.getText().toString());
hashMap.put("category", category.getSelectedItem().toString());
hashMap.put("publisher", FirebaseAuth.getInstance().getCurrentUser().getUid());
reference.child(postid).setValue(hashMap);
pd.dismiss();
startActivity(new Intent(PostActivityvideo.this, MainActivity.class));
finish();
} else {
Toast.makeText(PostActivityvideo.this, "Failed", Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(PostActivityvideo.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();
progressDialog.setMessage((int) progress + "");
}
});
}
} else {
Toast.makeText(PostActivityvideo.this, "No image selected", Toast.LENGTH_SHORT).show();
}
}
From what I can see you may have defined uploadTask as a Task.
To be able to call addOnProgressListener ,you'll want to declare it as an UploadTask.

Firebase android studio not inserting data correctly

This is the data being inserted the the correct one is the yay#gmail.com while the incorrectly inserted ones are the ones with a:Name
mAuth.createUserWithEmailAndPassword(email, pass)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
Teachers teachers = new Teachers(user, pass, email);
FirebaseDatabase.getInstance().getReference("Teachers")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(teachers).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()) {
Toast.makeText(RegisterTeacher.this, "Teacher has been registered!", Toast.LENGTH_SHORT).show();
Intent i = new Intent(RegisterTeacher.this, TeacherLogin.class);
startActivity(i);
}
else {
Toast.makeText(RegisterTeacher.this, "Failed to register!", Toast.LENGTH_SHORT).show();
}
}
});
} else {
Toast.makeText(RegisterTeacher.this, "Failed to register! Try again!", Toast.LENGTH_SHORT).show();
}
}
});

Upload multiple image to firebase and retrieve into viewpage

I want to upload multiple image to firebase and retrieve into view page . I am only able to upload the multiple image but getting only one Uri getdlownload link in Realtime database due to which only one image is fetching into view page
enter code here
private void sendDataToFirebase() {
progressBar.setVisibility(View.VISIBLE);
id = databaseReference.push().getKey();
Toast.makeText(this, "Sending", Toast.LENGTH_SHORT).show();
photoUri=new Uri[photoUris.size()];
for (i = 0; i < photoUris.size(); i++) {
photoUri[i] = photoUris.get(i);
// File fileUriPhoto = new File(SiliCompressor.with(this).
//
// compress(FileUtils.getPath(this, photoUri), new File(this.getCacheDir(), "AddPostPhotos")));
// Uri uri = Uri.fromFile(fileUriPhoto);
String imageName = UUID.randomUUID().toString();
final StorageReference imageFolder = mfirebaseStorage.child("AddPost/" + photoUri[i].getLastPathSegment());
imageFolder.putFile(photoUri[i]).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
imageFolder.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
progressBar.setVisibility(View.GONE);
addPostModel = new AddPostModel();
addPostModel.setCategories(spinner.getSelectedItem().toString().trim());
addPostModel.setSubcategories(spinner1.getSelectedItem().toString().trim());
addPostModel.setTitle(name.getText().toString().trim());
addPostModel.setAuthor(author.getText().toString().trim());
addPostModel.setPrice(price.getText().toString().trim());
addPostModel.setDesc(desc.getText().toString().trim());
addPostModel.setUserUid(mCurrentUser.getUid());
addPostModel.setPhoneNumaber(mCurrentUser.getPhoneNumber());
addPostModel.setDateTime(date);
addPostModel.setImageUrl(photoUri[i].toString());//Here is the problem//
addPostModel.setKey(id);
databaseReference.child(id).setValue(addPostModel);
}
});
}
}).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
Toast.makeText(AddPostFormActivity.this, "Post added", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(AddPostFormActivity.this,Dashboard.class);
startActivity(intent);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(AddPostFormActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
try this method...
imageFolder.putFile(photoUri[i]).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//Here you are get the download url
Task<Uri> urlTask =taskSnapshot.getStorage().getDownloadUrl();
Uri downloadUrl = urlTask.getResult();
final String sdownload_url = String.valueOf(downloadUrl);
progressBar.setVisibility(View.GONE);
addPostModel = new AddPostModel();
addPostModel.setCategories(spinner.getSelectedItem().toString().trim());
addPostModel.setSubcategories(spinner1.getSelectedItem().toString().trim());
addPostModel.setTitle(name.getText().toString().trim());
addPostModel.setAuthor(author.getText().toString().trim());
addPostModel.setPrice(price.getText().toString().trim());
addPostModel.setDesc(desc.getText().toString().trim());
addPostModel.setUserUid(mCurrentUser.getUid());
addPostModel.setPhoneNumaber(mCurrentUser.getPhoneNumber());
addPostModel.setDateTime(date);
addPostModel.setImageUrl(photoUri[i].toString());//Here is the problem//
addPostModel.setKey(id);
databaseReference.child(id).setValue(addPostModel);
}
}).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
Toast.makeText(AddPostFormActivity.this, "Post added", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(AddPostFormActivity.this,Dashboard.class);
startActivity(intent);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(AddPostFormActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});

How to get specific document id Firestore?

I was trying to get document id for updating a data, but instead it update all data. How to get document id Firestore?
Code :
firebaseFirestore.collection("Users").document(currentUser.getUid()).collection("Documents").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot documentSnapshot : task.getResult()) {
String getDocumentID = documentSnapshot.getId();
firebaseFirestore.collection("Users").document(currentUser.getUid()).collection("Documents").document(getDocumentID).update("inspectorName", inspectorName, "marketLocation", marketLocation).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(StartCounting.this, "Document updated", Toast.LENGTH_SHORT).show();
finish();
overridePendingTransition(0, 0);
startActivity(getIntent());
overridePendingTransition(0, 0);
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(StartCounting.this, "Error : " + e.toString(), Toast.LENGTH_LONG).show();
progressUpdated.dismiss();
}
});
}
}
}
});
Use set method with SetOptions.merge() to update only required field of document, but if you want to update only one document than don't use update query inside for loop.
firebaseFirestore.collection("Users").document(currentUser.getUid()).collection("Documents").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot documentSnapshot : task.getResult()) {
String getDocumentID = documentSnapshot.getId();
Map<String, Object> mapUser = new HashMap<>();
mapUser.put("inspectorName", inspectorName);
mapUser.put("marketLocation", marketLocation);
firebaseFirestore.collection("Users").document(currentUser.getUid()).collection("Documents").document(getDocumentID).set(mapUser, SetOptions.merge()).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(StartCounting.this, "Document updated", Toast.LENGTH_SHORT).show();
finish();
overridePendingTransition(0, 0);
startActivity(getIntent());
overridePendingTransition(0, 0);
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(StartCounting.this, "Error : " + e.toString(), Toast.LENGTH_LONG).show();
progressUpdated.dismiss();
}
});
}
}
}
});

error with updating user information firebase

so i am creating a sign up page and connect that with firebase users
i am recieving error with updating profile
my code goes as follow:
for creating new user i use
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
Log.v("SignUp", "222222222222222222222222222");
Toast.makeText(SignUp.this, "SignUp failed",
Toast.LENGTH_SHORT).show();
} else {
Log.v("SignUp", "333333333333333333333333333");
uploadImage();
}
}
});
and the uploadImage() method is
public void uploadImage() {
if (image != null) {
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference main = storage.getReferenceFromUrl("link to my account");
StorageReference storageReference = main.child("images/" + image.getLastPathSegment());
UploadTask uploadTask = storageReference.putFile(image);
//addonFailurelistener too
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Log.v("SignUp", "777777777777777777777777");
String download = taskSnapshot.getDownloadUrl().toString();
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.build();
//i tried here with .setDisplayName(name)
//and with setPhotoUri(Uri.parse(download)
FirebaseAuth.getInstance().getCurrentUser().updateProfile(profileUpdates).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.v("SignUp", "8888888888888888888888888888");
addDatabase();
} else {
FirebaseAuth.getInstance().getCurrentUser().delete().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.v("SignUp", "999999999999999999999999999");
Toast.makeText(SignUp.this, "Error Occuered While setting your account", Toast.LENGTH_LONG);
finish();
startActivity(new Intent(SignUp.this, SignUp.class));
} else {
Log.v("SignUp", "..........................");
Toast.makeText(SignUp.this, "Error Cannot be resolved \n please try with another Email", Toast.LENGTH_LONG);
finish();
}
}
});
}
}
});
}
});
}
and my logcat get output like that
V/SignUp: 333333333333333333333333333
V/SignUp: 777777777777777777777777
V/SignUp: ..........................
i followed the firebase guide but looks like i am doing something wrong
any idea why it doesnt work? thanks
i get it automatically resolved after waiting for 24 hours so i am assuming account get blocked for 24h after some number of logIn in a single day

Categories