How can I store equal strings os firebase ?
I have a class on firebase that allows me to add students but I don't know how do I create student1, student2, student3.
This is the code:
bSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!validateForm()) {
return;
}
if (mAuth.getCurrentUser() != null) {
String user_id = mAuth.getCurrentUser().getUid();
final DatabaseReference add_student_db = FirebaseDatabase.getInstance().getReference().child("Users").child(user_id).child("Alunos");
final String anome = aNome.getText().toString();
Map newPost = new HashMap();
newPost.put("Aluno", anome);
add_student_db.setValue(newPost);
}else {
Toast.makeText(AddStudent.this, "Erro ao Adicionar o Nome",
Toast.LENGTH_SHORT).show();
}
}
});
"Aluno" is student in portuguese.
My child stops at "Alunos" and I want it to create inside of "Alunos", "Aluno1", "Aluno2"...
Thanks.
Update:
I solved my problem by doing this:
if (mAuth.getCurrentUser() != null) {
String user_id = mAuth.getCurrentUser().getUid();
final String anome = aNome.getText().toString();
if (filePath != null){
final StorageReference add_student_sr = FirebaseStorage.getInstance().getReference().child("Users").child(user_id).child("Alunos").child(anome);
StorageReference riversRef = add_student_sr.child(anome+"_profilePic.jpg");
riversRef.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(getApplicationContext(), "File Uploaded ", Toast.LENGTH_LONG).show();
String downloadUrl = taskSnapshot.getDownloadUrl().toString();
String user_id = mAuth.getCurrentUser().getUid();
final DatabaseReference add_student_db = FirebaseDatabase.getInstance().getReference().child("Users").child(user_id).child("Alunos").child(anome);
Map newPost = new HashMap();
newPost.put("profilePic", downloadUrl);
add_student_db.setValue(newPost);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Toast.makeText(getApplicationContext(), exception.getMessage(), Toast.LENGTH_LONG).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
}
});
}
One way to handle this is to call push().
When you call push() Firebase creates a new unique location under the location. You can then call setValue on that new location
final DatabaseReference add_student_db = FirebaseDatabase.getInstance().getReference().child("Users").child(user_id).child("Alunos");
final String anome = aNome.getText().toString();
add_student_db.push().setValue(anome);
Every time you run this code a new child node will be created under /Users/$user_id/Alunos with "Aluno": "Name from aNome".
Related
in firebase I have two tables: itinerary with id, title, hour, minutes, seconds, description, level of difficulty and image while in review I have title, image and rating now I should insert the itinerary id, generated with getNewKey, in review so that one itinerary has several reviews. The created method is:
public void addReview() {
storageReference = FirebaseStorage.getInstance().getReference();
referenceDb = FirebaseDatabase.getInstance().getReference();
auth = FirebaseAuth.getInstance();
FirebaseUser firebaseUser = auth.getCurrentUser();
String titleReview = insertReviews_fragment.getTitleReview();
String descriptionReview = insertReviews_fragment.getDescriptionReview();
String voteItinerary = insertReviews_fragment.getVoteReview();
//String ItineraryId = String.valueOf(explore_fragment.getId());
String itineraryId = referenceDb.child("Itinerary").push().getKey();
ReviewDao reviewDao = new ReviewDao();
String reviewId = reviewDao.getNewKey();
if (images != null) {
StorageReference reviewRef = storageReference.child("review_image/").child(reviewId + ".jpg");
reviewRef.putFile(Uri.parse(String.valueOf(images))).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
reviewRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String uid = auth.getUid();
String email = firebaseUser.getEmail();
HashMap<String, Object> map = new HashMap<>();
map.put("titleReview", titleReview);
map.put("image", uri.toString());
map.put("email", email);
map.put("voteReview", voteItinerary);
map.put("descriptionReview", descriptionReview);
map.put("userId", uid);
map.put("reviewId", reviewId);
map.put("ItineraryId", itineraryId);
referenceDb.child("Reviews").child(reviewId).setValue(map).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
//APRO SCHERMATA List Review
Toast.makeText(insertReviews_fragment.getActivity(), "Operation successful, thanks for your feedback", Toast.LENGTH_SHORT).show();
openListReviewsFragment();
} else {
//ERRORE
Toast.makeText(insertReviews_fragment.getActivity(), "Operation failed. Please try again", Toast.LENGTH_SHORT).show();
}
}
});
}
});
} else {
Toast.makeText(insertReviews_fragment.getActivity(), task.getException().toString(), Toast.LENGTH_SHORT).show();
}
}
});
} else {
Toast.makeText(insertReviews_fragment.getActivity(), "Please add image", Toast.LENGTH_SHORT).show();
}
}
public void getAllItinerary(){
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference referenceDb = database.getReference("Itinerary");
itineraryList = new ArrayList<>();
Itinerary iter = new Itinerary();
itineraryList.clear();
referenceDb.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
Iterable<DataSnapshot> dataSnapsho1 = snapshot.getChildren();
for(DataSnapshot ds : dataSnapsho1) {
if(ds.child("titleItinerary").getValue() != null){
Itinerary iter = new Itinerary(
(String) ds.child("itineraryId").getValue(),
(String) ds.child("titleItinerary").getValue(),
(String) ds.child("descriptionItinerary").getValue(),
(String) ds.child("difficultyLevel").getValue(),
(String) ds.child("hours").getValue(),
(String) ds.child("minutes").getValue(),
(String) ds.child("seconds").getValue(),
String.valueOf(ds.child("image").getValue()));
iter.setEmail((String)ds.child("email").getValue());
itineraryList.add(iter);
}
}
adapterListItinerary = new AdapterListItinerary(getActivity(), itineraryList);
recyclerView.setAdapter(adapterListItinerary);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
But this way a new id code is associated with the itineraryId attribute in the reviews table. How can I fix?
I have implemented the code to upload the user photo to storage and retrieve it to the firestore and realtimeDB. the problem is when I set the imageuri to database :
then I'm (or user) updating a photo to firebase, the URI is successfully updated to the profile string..(firestore) and image srting (realtimeDB). but after some time/after the app closes, the photo not loading properly.(or its gone), it didn't use the firebase token as the download Uri.
its like this :
content://com.android.providers.media.documents/document/image%3A81399
then I attached another code to get the updated image URL from storage. But another problem
for now, Both Databases didn't store the URLs
I have attached the code below.
public class ProfileFragment extends Fragment {
public ProfileFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
CircleImageView profileImageView;
FragmentProfileBinding binding;
private Uri photoUri;
private String imageUrl;
FirebaseFirestore firestore;
FirebaseStorage storage;
FirebaseAuth auth;
StorageReference storageReference;
DocumentReference documentReference;
DatabaseReference DBreference;
String currentUserId;
User user; //class
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
binding = FragmentProfileBinding.inflate(inflater, container, false);
firestore = FirebaseFirestore.getInstance();
auth = FirebaseAuth.getInstance();
storage = FirebaseStorage.getInstance();
auth = FirebaseAuth.getInstance();
FirebaseUser fUser = FirebaseAuth.getInstance().getCurrentUser();
currentUserId = fUser.getUid();
documentReference = firestore.collection("Users").document(currentUserId);
storageReference = FirebaseStorage.getInstance().getReference().child("Profile Pictures");
DBreference = FirebaseDatabase.getInstance().getReference().child("Users");
update = binding.updateBtn;
profileImageView= binding.profilePhoto;
clickListener();
return binding.getRoot();
}
private void clickListener() {
profileImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
//noinspection deprecation
startActivityForResult(intent, 3);
}
});
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressDialog.show();
StorageReference reference = storage.getReference().child("Profile Pictures")
.child(FirebaseAuth.getInstance().getUid());
reference.putFile(photoUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
storageReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
imageUrl = uri.toString();
updateUserProfileToFirestore();
updateUserProfileToDataBase();
}
});
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull #NotNull UploadTask.TaskSnapshot snapshot) {
long totalSi = snapshot.getTotalByteCount();
long transferS = snapshot.getBytesTransferred();
long totalSize = (totalSi / 1024);
long transferSize = transferS / 1024;
progressDialog.setMessage("Uploaded " + ((int) transferSize) + "KB / " + ((int) totalSize) + "KB");
}
});
}
});
}
#SuppressWarnings("deprecation")
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (data.getData() != null) {
photoUri = data.getData();
// profileImageView.setImageURI(imageUri);
}
Toast.makeText(getContext(), "Photo selected!", Toast.LENGTH_SHORT).show();
}catch (Exception e){
Toast.makeText(getContext(), "Error"+e, Toast.LENGTH_SHORT).show();
}
}
private void updateUserProfileToFirestore() {
Map<String, Object> profile = new HashMap<>();
profile.put("profile", imageUrl);
final DocumentReference sDoc = firestore.collection("Users").document(FirebaseAuth.getInstance().getUid());
firestore.runTransaction(new Transaction.Function<Void>() {
#Override
public Void apply(#NonNull Transaction transaction) throws FirebaseFirestoreException {
DocumentSnapshot snapshot = transaction.get(sDoc);
transaction.update(sDoc, profile);
// transaction.update(sDoc, "name", binding.nameBox.getText() );
return null;
}
}).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
progressDialog.setMessage("updated!");
progressDialog.dismiss();
Toast.makeText(getContext(), "Photo Updated!", Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.setMessage("Can't upload");
progressDialog.dismiss();
Toast.makeText(getContext(), "Failed to update, try again later", Toast.LENGTH_SHORT).show();
}
});
// final DatabaseReference
}
// Realtime database
private void updateUserProfileToDataBase() {
HashMap<String, Object> map = new HashMap<>();
map.put("image", imageUrl);
DBreference.child(FirebaseAuth.getInstance().getUid())
.updateChildren(map)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
progressDialog.dismiss();
}
}).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
Toast.makeText(getContext(), "Success", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull #NotNull Exception e) {
Toast.makeText(getContext(), "Failed!", Toast.LENGTH_SHORT).show();
}
});
}
}
Solved! It's based on the storage reference. just changed to "reference".
because I already declared the storage reference. but I entered it twice
I keep getting this error and I have no idea where the problem is. I've tried the solutions suggested in similar topics but nothing worked for me.
FirebaseStorage storage;
StorageReference storageReference;
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
private void uploadImage() {
if(filePath != null)
{
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
final StorageReference ref = storageReference.child("images/"+ UUID.randomUUID().toString());
ref.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
HashMap<String,String> h = session.getUsersDetailsFromSession();
String uid = h.get("uid");
String titre = title.getEditText().getText().toString();
String tim = time.getEditText().getText().toString();
String desc = description.getEditText().getText().toString();
String img = String.valueOf(uri);
if(titre.equals("") || tim.equals("") || desc.equals("") || lat.equals("") || lon.equals("") || img.equals(""))
{
openDialogErr();
}
else
{
Reclamations rec = new Reclamations(uid,titre,desc,tim,lat,lon,img);
String key = FirebaseDatabase.getInstance().getReference().push().getKey();
DatabaseReference recl = FirebaseDatabase.getInstance().getReference("Reclamations").child(key);
recl.setValue(rec);
openDialogSucc();
}
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(Reclamation.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+"%");
}
});
}
}
I tried create folder per user by unique value (auth UID).
I did:
private String profileId;
private StorageReference mStorageRef;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = this.getArguments();
profileId = bundle.getString(Constants.PROFILE_ID_KEY);
mStorageRef = FirebaseStorage.getInstance().getReference("images");
StorageReference imageStorageRef = mStorageRef.child(profileId);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageName = "img" + timeStamp + "_.jpg";
imageStorageRef.child(imageName).putFile(picUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getUploadSessionUri();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
It is put all the images into specific profileId even when I sign out and connect with other profileId.
any help will be appraised
Your passing Constant Profile id : profileId = bundle.getString(Constants.PROFILE_ID_KEY);
Instead of just get user directly by using firebase auth.
if(FirebaseAuth.getInstance().getCurrentUser() != null){
uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
}else{
//do what you want
}
One one image uploading with different postkeys but i want to store all images under one postkey
This is the code where im uploading all the images to firebase storage and databse with post key but one one images are storing with different post key and i want to store all the uploaded images into one post key under blog in firebase databse. Please help me _This is th issue im facing from past few days and i want to retrieve all the uploaded images under one postkey
upload.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
UploadTask uploadTask;
if( selectedImageGridView.getChildCount()!= 0)
{
for ( int i = 0; i < selectedImages.size(); i++) {
blogimages = new ArrayList<>();
Uri uri = Uri.parse("file://"+selectedImages.get(i));
final String CurrentUser = firebaseAuth.getCurrentUser().getUid();
StorageReference reference = mstorageReference.child("Blog_pics/users").child(uri.getLastPathSegment());
uploadTask = reference.putFile(uri);
uploadTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
final Uri downloaduri = taskSnapshot.getDownloadUrl();
Log.v("DOWNLOAD URI", String.valueOf(downloaduri));
blogimages.add(downloaduri.toString());
Log.v("BLOGGIMAGES", String.valueOf(blogimages));
final String key = mdatabaseReference.push().getKey();
final String posttitle = desc.getText().toString();
final String CurrentUser = firebaseAuth.getCurrentUser().getUid();
int l = 0;
while (l < blogimages.size()){
Log.v("BLOGIMAGESSIZE", String.valueOf(blogimages.size()));
Map n = new HashMap();
int countingImage = 0;
n.put(String.valueOf("img" + countingImage), blogimages.get(l).toString());
Log.v("MapCount", String.valueOf(n));
mdatabaseReference.child(key).child("images").updateChildren(n).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
Toast.makeText(PhotoUploadActivity.this, "got download url", Toast.LENGTH_SHORT).show();
} else{
Toast.makeText(PhotoUploadActivity.this, "Failed to put in db", Toast.LENGTH_SHORT).show();
}
}
});
l++;
countingImage++;
}
}
}) .addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
}
});
}
}
}
});
you have to change this line
StorageReference reference = mstorageReference.child("Blog_pics/users").child(uri.getLastPathSegment());
to this lines: you have to put those lines befor the for loop
String userId = firebaseAuth.getCurrentUser().getUid();
StorageReference reference = mstorageReference.child("Blog_pics/users").child(userId);
then inside the loop
refrence.child(uri.getLastPathSegment());
uploadTask = reference.putFile(uri);
...