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
}
Related
I am trying to store an image url which I get by uploading it to a FirebaseStorage in a RealtimeDatabase. The former works without any problems. The image is created in the storage. However, in the OnSuccessListener I cannot save the URL in realtime. Then I get the following error:
com.google.firebase.database.DatabaseException: Failed to parse node with class class com.bkoubik.niceplace.AddNewPlace$4$1$1
AddNewPlace.java class:
StorageReference storageRef = FirebaseStorage.getInstance().getReference();
StorageReference mountainsRef = storageRef.child("images/"+ UUID.randomUUID() +".jpg");
Uri uploadUri = Uri.fromFile(new File(imageUri.toString()));
mountainsRef.putFile(uploadUri).addOnSuccessListener(new
OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
bar.setProgress(0);
status.setText("100 %");
mountainsRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
//UploadUriForPlace up = new UploadUriForPlace(uri.toString());
String placeId = ref.push().getKey();
ref.child(new Date().toString()).setValue(uri.toString(), new OnSuccessListener() {
#Override
public void onSuccess(Object o) {
Toast.makeText(AddNewPlace.this,"Ist oben, danke!",Toast.LENGTH_LONG);
}
});
}
});
}
});
Uri is not empty:
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);
...
I'm trying to store an image with some relevant data regarding that image in Firebase. When I press the save button, the image is saved into my storage folder no problem, but the Database attributes just aren't being saved and I can't figure out why.
This is my code:
String Storage_Path = "All_Book_Images";
String Database_Path = "All_Books";
Uri FilePathUri;
StorageReference storageReference;
DatabaseReference databaseReference;
int Image_Request_Code = 71;
ProgressDialog progressDialog;
Button imageButton, saveButton;
EditText title, author, price, category, additionalInfo;
ImageView SelectImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bookupload);
SelectImage = (ImageView) findViewById(R.id.book_image);
title = (EditText) findViewById(R.id.title_text);
author = (EditText) findViewById(R.id.author_text);
price = (EditText) findViewById(R.id.price_text);
category = (EditText) findViewById(R.id.category_text);
additionalInfo = (EditText) findViewById(R.id.info_text);
storageReference = FirebaseStorage.getInstance().getReference();
databaseReference = FirebaseDatabase.getInstance().getReference(Database_Path);
}
public void imageButton(View view){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Image"),0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 0 && resultCode == RESULT_OK){
FilePathUri = data.getData();
try{
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), FilePathUri);
SelectImage.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String getActualImage(Uri uri){
ContentResolver contentResolver = getContentResolver();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri));
}
public void uploadData(View view){
if(FilePathUri != null){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading");
progressDialog.show();
StorageReference reference = storageReference.child(Storage_Path + System.currentTimeMillis() + "." + getActualImage(FilePathUri));
reference.putFile(FilePathUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
String Title = title.getText().toString();
String Author = author.getText().toString();
String Price = price.getText().toString();
String Category = category.getText().toString();
String AdditionalInfo = additionalInfo.getText().toString();
Book book = new Book(taskSnapshot.getDownloadUrl().toString(), Title, Author, Price, Category, AdditionalInfo);
String id = databaseReference.push().getKey();
databaseReference.child(id).setValue(book);
progressDialog.dismiss();
Toast.makeText(getApplicationContext(),"Data uploaded",Toast.LENGTH_LONG).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_LONG).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#SuppressWarnings("VisibleForTests")
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double totalProgress = (100*taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
progressDialog.setMessage("Uploaded % " + (int)totalProgress);
}
});
} else {
// show message
Toast.makeText(getApplicationContext(),"Please select data first",Toast.LENGTH_LONG).show();
}
}
What's causing this to interact with the Storage aspect of Firebase fine, but not the Database?
Check this snippet from Firebase Official Doc, i have writen some of your requirement inside, but you get the idea
private void writeNewPost(String Title, String Price, String Author) {
String key = databaseReference.push().getKey();
Post post = new Post(Title, Price, Author);
Map<String, Object> postValues = post.toMap();
Map<String, Object> books = new HashMap<>();
books.put(Title, postValues);
books.put(Price, postValues);
books.put(Author, postValues);
mDatabase.child(key).updateChildren(books);
}
for more info : https://firebase.google.com/docs/database/android/read-and-write
PS: you can use updateChildren() or setValue() , it depends which one you need.
If you use setValue() in this way, the data is overwritten at the specified location, including the secondary nodes.
You can make simultaneous updates to multiple locations in the JSON tree with a single call to updateChildren().
It turns out that my code was actually working OK, I just had the rules of my Firebase Database set up incorrectly. The code I posted in the question should work for anyone trying to implement this.
Here is my Firebase FireStone Database Structure:
MainPosts
7YBc5LhUwU2wQB4ZybOl
IcInT5YEPKL2TVSAADP2
tiUCi5IUuuCA2BT5Ldda
This is my Code:
firebaseFirestore.collection("MainPosts").addSnapshotListener(SingleVideoActivity.this, new EventListener<QuerySnapshot>() {
#Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
for (DocumentChange doc : documentSnapshots.getDocumentChanges()) {
if (doc.getType() == DocumentChange.Type.ADDED) {
String blogPostId = doc.getDocument().getId();
BlogPost blogPost = doc.getDocument().toObject(BlogPost.class).withId(blogPostId);
blog_list.add(blogPost);
blogListRecyclerAdapter.notifyDataSetChanged();
}
}
}
});
What i want to do to get random document like from this three :-
7YBc5LhUwU2wQB4ZybOl
IcInT5YEPKL2TVSAADP2
tiUCi5IUuuCA2BT5Ldda
I think you can do it by save documents with a specific name. Upload a file this way:
StorageReference storageRef = storage.getReference();
//find your way to keep thees values
string documentName = "1";//if it is the first file, if the file is second post the value should be 2
string documentExtention = ".doc";
storageRef.child("MainPosts/"+ documentName + documentExtention);
When you have to download:
Get a random:
Random rand = new Random();
int lastUploadedFileNumber = 50; // if you have 50 files in FirebasStore
int randomNumber = rand.nextInt(lastUploadedFileNumber) + 1;
Then download the random file in local file:
StorageReference downloadRef = storageRef.child("MainPosts/"+ randomNumber.toString() + documentExtention);
File localFile = File.createTempFile("radomFileName", documentExtention);
downloadRef .getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
// Local temp file has been created
showFile(localFile); //implement a way to show the file
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
}
});
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".