How to get the URL of multiple images in Firebase - java

I'm storing multiple images at once in Firebase Storage and I need to get the URL of each one of them in the Firebase databse.
Here's the code:
private void SaveVersus() {
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();
List<Uri> uri = Arrays.asList(imageUri,imageUri2);
storeMultipleImages(uri);
}
else if(imageUri!=null&&imageUri2!=null&&imageUri3!=null&&imageUri4==null){
//Save3ImagesFirebase();
List<Uri> uri2 = Arrays.asList(imageUri,imageUri2,imageUri3);
storeMultipleImages(uri2);
}
else if(imageUri!=null&&imageUri2!=null&&imageUri3!=null&&imageUri4!=null){
//Save4ImagesFirebase();
List<Uri> uri3 = Arrays.asList(imageUri,imageUri2,imageUri3,imageUri4);
storeMultipleImages(uri3);
}
}
public void storeImage(Uri imageUri) {
StorageReference filepath = mStorage.child("Versus Images").child(imageUri.getLastPathSegment());
filepath.putFile(imageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()){
downloadURL = task.getResult().getUploadSessionUri().toString();
Toast.makeText(ImageVersus.this, "Versus Published", Toast.LENGTH_SHORT).show();
GetInDB();
}
else{
Toast.makeText(ImageVersus.this, "..Error..", Toast.LENGTH_SHORT).show();
}
}
});
}
private void GetInDB() {
mDatabase.child(current_userID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
String username = dataSnapshot.child("Username").getValue().toString();
HashMap InfoMap = new HashMap<>();
InfoMap.put("username",username);
InfoMap.put("imageUrl",downloadURL);
versusDBRef.child(current_userID).updateChildren(InfoMap);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
public void storeMultipleImages(List<Uri> imageUris) {
for (Uri uri : imageUris) {
storeImage(uri);
}
}
The problem is that, in the hashmap, I can only put the URL of one image and I need to get multiple URLs depending on what the amount of pictures the user select, if they chose two, then in the hashmap must be two URL's and so on.

Related

Check if the user in the database firebase exists

I would like to check if the user in the database exists. with this line of codes, it says that it exists and also that it does not exist. I want to make the code read-only if the name exists in one of the registers
enter image description here
Firebase database
private void Criar_Conta() {
databaseReference_users.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
if (snapshot.child("usuario").getValue().equals(Usuario.getText().toString()) && snapshot.getKey().equals(Usuario.getText().toString()) && snapshot.getKey().equals(snapshot.child("usuario").getValue())) {
Toast.makeText(Sign_Up.this, "Usuário Existente", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(Sign_Up.this, "Gravar ...", Toast.LENGTH_SHORT).show();
//Gravar_Dados();
}
}
} else {
Gravar_Dados();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(Sign_Up.this, databaseError.getMessage(), Toast.LENGTH_LONG).show();
Swipe.setRefreshing(true);
}
});
This is my code sample I hope this helps you
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String phoneTxt = phone.getText().toString();
final String passwordTxt = password.getText().toString();
if (phoneTxt.isEmpty() || passwordTxt.isEmpty()){
Toast.makeText(Login.this, "Please Enter Your Phone Number Or Password", Toast.LENGTH_SHORT).show();
}else {
databaseReference.child("users").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.hasChild(phoneTxt)){
final String getpassword = snapshot.child(phoneTxt).child("password").getValue(String.class);
if (getpassword.equals(passwordTxt)){
Toast.makeText(Login.this, "Successfully login! ", Toast.LENGTH_SHORT).show();
startActivity(new Intent(Login.this,HomeScreen.class));
finish();
}
else{
Toast.makeText(Login.this, "Wrong Password", Toast.LENGTH_SHORT).show();
}
}
else {
Toast.makeText(Login.this, "Wrong Phone Number!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
});
To be able to check if a specific user exists in the database, you should only perform a get(), and not attach a ValueEventListener. Assuming that the users are direct children of your Firebase Realtime Database root, in code, will be as simple as:
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
String usuario = Usuario.getText().toString();
DatabaseReference usuarioRef = db.child(usuario);
usuarioRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
DataSnapshot snapshot = task.getResult();
if(snapshot.exists()) {
Log.d("TAG", "User exists.");
} else {
Log.d("TAG", "User doesn't exist.");
}
} else {
Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
}
}
});

My hashmap is not getting implemented in firebase database

I'm using this hashmap to transfer the username from one child(Users) to another(Notes) in database.
In my app you can create as well as update notes.
I want that every time a note is created or updated in the database a username is added along with the note. the username is saved in the users child.
But when the note is created the username doesn't show up. But when the note is updated, it is added in the child.
here is the code:
fAuth = FirebaseAuth.getInstance();
fNotesDatabase = FirebaseDatabase.getInstance().getReference()
.child("Notes").child(fAuth.getCurrentUser().getUid());
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
current_user_id = fAuth.getCurrentUser().getUid();
btnCreate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String title = etTitle.getText().toString().trim();
String content = etContent.getText().toString().trim();
if (!TextUtils.isEmpty(title) && !TextUtils.isEmpty(content)) {
createNote(title, content);
putUsername();
} else {
Snackbar.make(view, "Fill empty fields", Snackbar.LENGTH_SHORT).show();
}
}
});
private void putUsername() {
UsersRef.child(current_user_id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String username = snapshot.child("username").getValue().toString();
HashMap usernameMap = new HashMap();
usernameMap.put("username", username);
fNotesDatabase.child(noteID).updateChildren(usernameMap);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
I'm not able to understand as how come the username is added when the note is updated but not when the note us created.
I have updated the second note thats why there is a username but when is simply created the upper one there username is not showing.
EDIT
putData method :
private void putData() {
if (isExist) {
fNotesDatabase.child(noteID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild("title") && dataSnapshot.hasChild("content")) {
String title = dataSnapshot.child("title").getValue().toString();
String content = dataSnapshot.child("content").getValue().toString();
etTitle.setText(title);
etContent.setText(content);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
createNote method:
private void createNote(String title, String content) {
if (fAuth.getCurrentUser() != null) {
Calendar calFordDate = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
saveCurrentDate = currentDate.format(calFordDate.getTime());
if (isExist) {
Map updateMap = new HashMap();
updateMap.put("title", etTitle.getText().toString().trim());
updateMap.put("content", etContent.getText().toString().trim());
updateMap.put("timestamp", ServerValue.TIMESTAMP);
updateMap.put("date",saveCurrentDate);
fNotesDatabase.child(noteID).updateChildren(updateMap);
SendUsersToPostActivity();
Toast.makeText(this, "Article updated", Toast.LENGTH_SHORT).show();
} else {
final DatabaseReference newNoteRef = fNotesDatabase.push();
final Map noteMap = new HashMap();
noteMap.put("title", title);
noteMap.put("content", content);
noteMap.put("timestamp", ServerValue.TIMESTAMP);
noteMap.put("date",saveCurrentDate);
Thread mainThread = new Thread(new Runnable() {
#Override
public void run() {
newNoteRef.setValue(noteMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(NewNoteActivity.this, "Article Created", Toast.LENGTH_SHORT).show();
SendUsersToPostActivity();
} else {
Toast.makeText(NewNoteActivity.this, "ERROR: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
});
mainThread.start();
}
}
}
It's hard to be certain, but I don't see where you set the noteID value that putUsername depends on.
In general though, I'd recommend changing createNote to take all the data that it needs for the new note, including the user name:
btnCreate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String title = etTitle.getText().toString().trim();
String content = etContent.getText().toString().trim();
if (!TextUtils.isEmpty(title) && !TextUtils.isEmpty(content) && fAuth.getCurrentUser() != null) {
UsersRef.child(current_user_id).child("username").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String username = snapshot.getValue(String.class);
createNote(title, content, current_user_id, username);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException()
}
});
} else {
Snackbar.make(view, "Fill empty fields", Snackbar.LENGTH_SHORT).show();
}
}
});
private void createNote(String title, String content, String uid, String username) {
Calendar calFordDate = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
saveCurrentDate = currentDate.format(calFordDate.getTime());
Map updateMap = new HashMap();
updateMap.put("title", title);
updateMap.put("content", content);
updateMap.put("timestamp", ServerValue.TIMESTAMP);
updateMap.put("date",saveCurrentDate);
updateMap.put("uid",uid);
updateMap.put("username",username);
final DatabaseReference noteRef = isExist ? fNotesDatabase.push() : fNotesDatabase.child(noteID);
noteRef.updateChildren(noteMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(NewNoteActivity.this, "Article "+(isExists ? "updated" : "created"), Toast.LENGTH_SHORT).show();
SendUsersToPostActivity();
} else {
Toast.makeText(NewNoteActivity.this, "ERROR: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
Some of the changes in this code versus yours:
Looks up the user name before creating the new note. Uses a addListenerForSingleValueEvent for this, to ensure we only do this once for every button click.
Only loads the username child of the user profile, since that's all you use.
Use the values you pass into createNote instead of recalculating them from the UI views.
Only has a single write to the database, as updateChildren works fine for creating the initial data too.
There is no need to run the Firebase setValue call on a new thread, as Firebase runs it off the main thread already.
Please don't leave onCancelled empty, as it may hide important error messages.

Validate if data already exist in firebase

I am trying to find if the data already exist in the database. However it doesn't enter the loop. It always go to the else
This is my validation part, it always goes to the else part
full code is in pastebin
private void validate(final String Song) {
final DatabaseReference RootRef;
RootRef = FirebaseDatabase.getInstance().getReference();
RootRef.addListenerForSingleValueEvent(new ValueEventListener()
{
public void onDataChange(DataSnapshot dataSnapshot)
{
if (!(dataSnapshot.child("Participants").child(Song).exists()))
{
HashMap<String, Object> userdataMap = new HashMap<>();
userdataMap.put("song", Song);
RootRef.child("Participants").child(Song).updateChildren(userdataMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task)
{
if (task.isSuccessful())
{
Toast.makeText(Register.this, "This song already exists.", Toast.LENGTH_SHORT).show();
}
}
});
}
else {
Toast.makeText(Register.this, "Your have choosed your song", Toast.LENGTH_SHORT).show();
// Toast.makeText(Register.this, "Please try again.", Toast.LENGTH_SHORT).show();
}}
public void onCancelled(DatabaseError databaseError) {
}
});
}
RootRef = FirebaseDatabase.getInstance().getReference().child("Participants").child(Song);
RootRef.addListenerForSingleValueEvent(new ValueEventListener()
{
public void onDataChange(DataSnapshot dataSnapshot)
{
if (dataSnapshot.exists())
{
Toast.makeText(Register.this, "This song already exists.", Toast.LENGTH_SHORT).show();
}
else {
HashMap<String, Object> userdataMap = new HashMap<>();
userdataMap.put("song", Song);
RootRef.setValue(userdataMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task)
{
if (task.isSuccessful())
{
Toast.makeText(Register.this, "This song successfully added", Toast.LENGTH_SHORT).show();
}
}
});
}}
public void onCancelled(DatabaseError databaseError) {
}
});
If you want to check exist a song, you can give it as a reference. If datasnapshot is exists then your database has the song. If not, you can add the song to the database.

Why List<String> are not inserted in Firebase Realtime Database

I created an app and I want to store some images in a Firebase Storage, this is working fine, those images are uploaded, but I want to save their path in the database and those values are not inserted.
Let me show you what I did:
I'm not showing you the entire function. Only the code that points to my problem.
List<String> picturesUrls = new ArrayList<String>(); //This is declared globaly
buttonSigningUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uploadFile(mProfilePic,"profilePicture");
uploadFile(mIdPhoto,"idPicture");
uploadFile(mCriminalRecord,"criminalRecordPicture");
final List<String> pictureUrls = picturesUrls;
mFirebaseAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
final CarrierUser carrierUser;
carrierUser = new CarrierUser(
pictureUrls
);
FirebaseDatabase.getInstance().getReference("User")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(carrierUser).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()) {
Toast.makeText(SignupCarrier.this,"Your request has been sent for approval", Toast.LENGTH_LONG).show();
sendEmail(email, fullname);
openLogin();
}
}
});
}
}
});
}
});
Upload File Function :
private void uploadFile(Uri path,String forWho) {
if(path != null) {
StorageReference fileReference = mStorageRef.child(editemail.getText().toString()+"-"+forWho+"-"+System.currentTimeMillis()+"."+getFileExtension(path));
mUploadTask = fileReference.putFile(path)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
picturesUrls.add(taskSnapshot.getUploadSessionUri().toString());
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(SignupCarrier.this, e.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
}
And the Object:
import java.util.List;
public class CarrierUser {
public List<String> picturesUrls;
public CarrierUser() {
}
public CarrierUser(List<String> picturesUrls) {
this.picturesUrls = picturesUrls;
}
}
I do have another values and fields, but they are inserted, only this list with paths is not. Maybe I did something wrong when I add a path to that list, but I can't figure out what exactly is wrong. Can you please help me out? Thank you very much.

Unable to put image url to Firestore database after uploading the image to firebase storage

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.

Categories

Resources