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
}
});
Related
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);
...
I would like to get first data inside Arraylist but my code getting issue that String img contain null data. here is my code :
private List<String> imagedUploaded = new ArrayList<>();
....
private void uploadImageFile(List<Uri> imgUrl) {
for (Uri uri : imgUrl) {
StorageReference fileToUpload = storageRef.child(productID).child(getFileName(uri));
fileToUpload.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
listImageSelectedAdapter.notifyDataSetChanged();
imagedUploaded.add(taskSnapshot.getDownloadUrl().toString()); // get image downloadurl
**defImg = imagedUploaded.get(0);**
productImage = product_Ref.child("product_image").child(productID);
productImage.setValue(imagedUploaded);
selectedImages.clear();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getContext(), "Upload Image Failed", Toast.LENGTH_SHORT).show();
}
});
}
}
here when i want to call index result
uploadProduct() {
product = product_Ref.child(path1).child(path2).child(path3).child(productID);
DataUploadProduct data = new DataUploadProduct();
data.setName(etProductName.getText().toString());
data.setPrice(etPrice.getText().toString());
**data.setDef_image(defImg);**
data.setWeight(etWeight.getText().toString());
data.setDescription(etDescription.getText().toString());
product.setValue(data);
}
in this case imagedUploaded contain :
0 = http://www.url.com1
1 = http://www.url.com2
2 = http://www.url.com3
3 = http://www.url.com4
i want to get data only index 0, how i can do that?
I have stored the url of the pdf file stored in firebase storage, in database inside the node Pdf. I am trying to download the file from firebase storage with the help of the url stored inside the database.
public class DownloadFile extends AppCompatActivity{
DatabaseReference databaseReference= FirebaseDatabase.getInstance().getReference();
String root_child="my book";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
databaseReference.child("Pdf").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChild(root_child))
{
String url=dataSnapshot.child(root_child).getValue().toString();
StorageReference island=storageRef.child("books").child(root_child).child(url);
island.getFile(file).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
pdfView.fromFile(file).load();
}
});
}
}
The problem is nothing really shows up inside the pdf view. When I debug the app I found that StorageReference island=storageRef.child("books").child(root_child).child(url); is not creating the right reference. In short the file is not downloading. Since the file name varies according to what users upload, it is not possible for me to specify the file name hence I used 'child(url)' so that it can search the file using the url but I am not sure if that is the right way to search a file.Any help is appreciated.
As you have discovered while debugging, the file is not downloading because the reference is not correct.
How are you getting info from the user about which file to download ?
I believe you must be showing him the list of files which he/she has uploaded. So in that list you can store the info about the file_name. Now when the user clicks on the list-item, you can have the correct reference since you know the file_name from the clicked list-item.
In the same matter i give you a different approach that i use when i was getting that same error.
actually i save file in Firebase Storage with the name of post_id to which the file is related and then give shot to the following code
give a look
private void downloadFile(final String postKey) {
File cFile = new File(getContext().getCacheDir(), "app Directory");
final File cLocalFile = new File(cFile, postKey);
if (!rootPath.exists()) {
rootPath.mkdirs();
}
if (!cFile.exists()) {
cFile.mkdirs();
}
final FileDownloadTask downloadingTask = mStorage.child(postKey).getFile(cLocalFile);
downloadingTaskProgress(downloadingTask, cLocalFile);
}
private void downloadingTaskProgress(FileDownloadTask downloadingTask, final File cLocalFile) {
downloadingTask.addOnProgressListener(new OnProgressListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onProgress(final FileDownloadTask.TaskSnapshot taskSnapshot) {
double progressSize = (100.0 * taskSnapshot.getBytesTransferred())
/ taskSnapshot.getTotalByteCount();
}
}).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(getActivity(), "File download complete: " + model.fileName, Toast.LENGTH_SHORT).show();
try {
writeToStorage(cLocalFile);
} catch (IOException e) {
e.printStackTrace();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Toast.makeText(getContext(), "local file not created: " +
exception.toString(), Toast.LENGTH_LONG).show();
}
});
}
private void writeToStorage(File src) throws IOException {
FileChannel inChannel = new FileInputStream(src).getChannel();
FileChannel outChannel = new FileOutputStream(localFile).getChannel();
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} finally {
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
}
give some modification as per your need and this approach could work as it is in mine....
I got the solution of the problem myself.
I used StorageReference island=storage.getReferenceFromUrl(url); instead of StorageReference island=storageRef.child("books").child(root_child).child(url); . This solved my problem.
I have been searching for this problem, but I have not found any solution here. My problem is that when I post new item to firebase storage everything works well, but when I try to download it, directory folder is created successfully, but file is not downloaded as it shows me this error exception:
com.google.firebase.storage.StorageException: Object does not exist at
location
My code here:
#Override
public void onButtonDownloadClick(View view, final int position) {
String name = list.get(position).getRemoteName();
File storagePath = new File(Environment.getExternalStorageDirectory(), "FromFiles");
// Create direcorty if not exists
if(!storagePath.exists()) {
storagePath.mkdirs();
}
final File myFile = new File(storagePath, list.get(position).getRemoteName());
islandRef = storageReference.child(uid).child("files").child(name);
islandRef.getFile(myFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
// Local temp file has been created
Toast.makeText(getActivity(), "Succeed", Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
Toast.makeText(getActivity(), exception.toString(), Toast.LENGTH_LONG).show();
}
});
}
});
When I press button, file should be downloaded, however only directory is created.
This is working example for the firebase download and check the download path, the object should exist in the bucket.
// Initialize Storage
//storage
mStorage = FirebaseStorage.getInstance("gs://<bucket_name>");
mStorageRef = mStorage.getReference();
final StorageReference downloadRef;
downloadRef = mStorageRef.getRoot().child(downloadPath);
try {
File output = new File(Environment.getExternalStorageDirectory() + File.separator + Config.MY_VIDEOS_PATH);
if (!output.exists()) {
output.mkdir();
}
localFile = new File(output, downloadId);
} catch (Exception e) {
e.printStackTrace();
}
// Download and get total bytes
downloadRef.getFile(localFile)
.addOnProgressListener(new OnProgressListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onProgress(FileDownloadTask.TaskSnapshot taskSnapshot) {
showProgressNotification(1,title, "",
taskSnapshot.getBytesTransferred(),
taskSnapshot.getTotalByteCount());
}
})
.addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Log.d(TAG, "download:SUCCESS");
// Send success broadcast with number of bytes downloaded
broadcastDownloadFinished(downloadPath, taskSnapshot.getTotalByteCount());
showDownloadFinishedNotification(downloadPath, (int) taskSnapshot.getTotalByteCount());
// Mark task completed
taskCompleted();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Log.w(TAG, "download:FAILURE", exception);
Log.w(TAG, "download:FAILURE", exception.getCause());
// Send failure broadcast
broadcastDownloadFinished(downloadPath, -1);
showDownloadFinishedNotification(downloadPath, -1);
// Mark task completed
taskCompleted();
}
});
Let us assume that your image.jpg in the photos folder then the downloadPath photos/image.jpg
Check Firebase Rules ..!
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if request.auth != null;
}
}
}
private FirebaseAuth mAuth;
private FirebaseDatabase mdatabase;
private DatabaseReference mdatabaseReference;
StorageReference mFStorage;
StorageReference filePath;
mAuth = FirebaseAuth.getInstance();
mdatabase = FirebaseDatabase.getInstance();
mdatabaseReference = mdatabase.getReference();
mFStorage= FirebaseStorage.getInstance().getReference();
filePath=mFStorage.child("audio").child(audioId+".mp3");
filePath.putFile(imageGalleryUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
dialog.dismiss();
DownloadUrl=taskSnapshot.getDownloadUrl();
Log.d(TAG,"DownloadUrl.toString()");
//download link for file
}
});
then use Download Manager To download File like for Audio
Context ctx=MainActivty.this;
DownloadManager downloadManager = (DownloadManager)ctx.getSystemService(DOWNLOAD_SERVICE);
//Your Url here
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setDescription("Downloading a file");
long id = downloadManager.enqueue(request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI |DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false)
.setTitle("File Downloading...")
.setDescription("Audio File Downloading...!")
.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "/Audio/"+audioName+".mp3"));