I wrote a program that uploads a series of data to firebase
My problem is that when new data is uploaded, the previous contents of the file in Firebase are deleted and new data is replaced.
It is possible to guide the previous data to be added to the new data
enter image description here
String key_press ="key pressed :"+sb;
reference= FirebaseStorage.getInstance().getReference().child("Dcument");
reference.child("file.txt").putBytes(sb.toString().getBytes()).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Toast.makeText(MyAccessibilityService.this, "file upload seuccessfully", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MyAccessibilityService.this, e.toString(), Toast.LENGTH_SHORT).show();
}
});
When you write data to a path in Cloud Storage (with Firebase or any of the other SDKs) it replaces any data that existed at that path. There is no way to tell Cloud Storage to merge the data, as it treats all files/objects as blobs and doesn't have any knowledge about the file's structure.
So you will either have to read the existing data, merge that with your update, and then write the result to Cloud Storage, or store the new data as a separate file in Cloud Storage.
Related
I am making an App in Android Studio and I am using Firebase Storage to store user information in individual text files, to later be uploaded to the app's user dashboard. I have written all the code to do this and I have followed the Firebase documentation to the best of my ability. When I run my app (tested on my Motorola moto e5 phone) everything runs perfectly, and then the file with the user information is created. Then it is supposed to be uploaded to the Firebase Storage section, and then it should be destroyed. I know that the first and last events happened.
Problem
However, when I go into Firebase to check that the file is there it is not. So I go to check to see if Android Studio returned any errors and I see no errors and that everything ran smoothly, but I don't see the files in firebase that were supposed to be uploaded. So then I looked all over the internet, fourm after fourm, documentation after documentation, and I tried it all. If you find something that might help me that I haven't found please kindly share the link. Also if you know what the problem is please share.
Troubleshooting Methods
To be more specific these are some things I have tried:
Clean Project
Invalidate Caches and Restart
Change SDK Version in the dependencies in the build.gradle file and made sure they were all up to date and tried old ones too
Wrote the example code they give in the documentation in a different project and it still didn't work
Kept writing code to see if the file was hidden and the Storage Reference returned null
Tried removing the file.delete(); line
Code
This method when called should create a "goal" the user wants to accomplish by saving their input in a file called 0.txt, 1.txt, 2.txt and so on. Then the method should upload the file to Firebase Storage, and that's where the problem is. It won't appear in the database.
private void createGoal(String activity, String timeframe, String number, String unit) throws IOException {
//creates an instance of the Main Dashboard class inorder to access the variable counterString.
MainDashboard dBoard = new MainDashboard();
//Names the 0.txt, 1.txt, 2.txt, and so on
file = new File(dBoard.counterString + ".txt");
//Creates the actual file
file.createNewFile();
//Creates the writer object that will write to the file
FileWriter writer = new FileWriter(file);
//Writes to the text file
writer.write(activity + " : " + "0 / "+ number + " " + unit + " in " + timeframe);
//Closes the Writer
writer.close();
//Creates a Uri from the file to be uploaded
upload = Uri.fromFile(new File(activity + ".txt"));
//Uploads the file exactly as the documentation says, but it doesn't work
UploadTask uploadTask = storageRef.putFile(upload);
//Deletes the file from the local system
file.delete();
}
Any Ideas Are Appreciated.
When you call putFile Firebase starts uploading the data in the background, so that your user can continue to use the app. But your code immediately calls delete on the local file after that, which means you're deleting the local file before Firebase has completed (or possibly even started) uploading it.
The trick is to monitor the upload progress as shown in the Firebase documentation, and only delete the local file once the upload has completed.
Based on the example from that documentation:
// Listen for state changes, errors, and completion of the upload.
uploadTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
System.out.println("Upload is " + progress + "% done");
}
}).addOnPausedListener(new OnPausedListener<UploadTask.TaskSnapshot>() {
#Override
public void onPaused(UploadTask.TaskSnapshot taskSnapshot) {
System.out.println("Upload is paused");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Handle successful uploads on complete
// ...
//Deletes the file from the local system
file.delete();
}
});
I would like to upload my SQLite database File to Firebase Storage. My problem is that I can only find tutorials where the user has to choose the file manually, but I would like to send a fixed file, so you can't send other data to Firebase storage.
How can I do that?
Thank you.
First get the reference to the firebase storage
// Create a storage reference from our app
StorageReference storageRef = storage.getReference();
Then to upload the file do the following:
Uri file = Uri.fromFile("sqlite_file");
StorageReference filesRef = storageRef.child("files");
uploadTask = filesRef.putFile(file);
// Register observers to listen for when the download is done or if it fails
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, etc.
// ...
}
});
I see that the Firebase has already a new beta version released, called Cloud Firestore. In the documentation all operations with the documents are described very well, but I am not able to find anything about uploading and downloading media files into the Cloud Firestore using Android...
Does anyone has any information/tutorial etc for uploading/downloading media files (for example mp3 files and images)?
Thank you very much in advance for the answers!
You can't store files to Firebase Cloud Firestore instead you can use the combination of Firebase Storage and Firebase Cloud Firestore to active the desired functionality.
Firebase Storage is to storage files and download from it.
Firebase Realtime Database is to store json no-sql database on it.
Firebase Cloud Firestore is advanced version of Firebase realtime database the difference from Realtime database is that it is Document based non-sql database.
Suppose you need to develop an application with database and storage you need combination of any of Database with Firebase Storage. Store files in firebase storage and save their urls in firebase realtime or firebase cloud firestore for downloading and uploading them.
To Upload file on firebase storage :
FirebaseStorage firebaseStorage;
//for firebase storage
firebaseStorage = FirebaseStorage.getInstance();
StorageReference storageReference;
storageReference = firebaseStorage.getReferenceFromUrl("url");
final StorageReference imageFolder = storageReference.child("" + imageName);
imageFolder.putFile(saveUri).addOnSuccessListener(new OnSuccessListener < UploadTask . TaskSnapshot >() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//submitted sucessfully
imageFolder.getDownloadUrl().addOnSuccessListener(new OnSuccessListener < Uri >() {
#Override
public void onSuccess(Uri uri) {
Log.wtf(TAG, "download image path : " + uri.toString());
//now you have path to the uploaded file save this path to your database
uploadDataToUserUploadedImage(uri);
}
}).addOnFailureListener(new OnFailureListener () {
#Override
public void onFailure(#NonNull Exception e) {
getMvpView().stopProgressLoading();
getMvpView().onError("Fail to submit feedback " + e.getMessage());
getMvpView().hideLoading();
return;
}
});
}
}).addOnProgressListener(new OnProgressListener < UploadTask . TaskSnapshot >() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress =(100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
getMvpView().publishProgress((int) progress);
Log.d(TAG, "onProgress: " + progress);
}
}).addOnFailureListener(new OnFailureListener () {
#Override
public void onFailure(#NonNull Exception e) {
getMvpView().hideLoading();
getMvpView().stopProgressLoading();
getMvpView().onError("Error: " + e.getMessage());
}
});
I have uploaded some files into Firebase directory and I want to list them and download one by one.There is no API/Documentation fo this.Could you help me ?
As of July 2019, version 18.1.0 of the Cloud Storage SDK now supports listing all objects from a bucket. You simply need to call listAll() in a StorageReference:
StorageReference storageRef = FirebaseStorage.getInstance().getReference();
// Now we get the references of these images
storageRef.listAll().addOnSuccessListener(new OnSuccessListener<ListResult>() {
#Override
public void onSuccess(ListResult result) {
for(StorageReference fileRef : result.getItems()) {
// TODO: Download the file using its reference (fileRef)
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(Exception exception) {
// Handle any errors
}
});
If you want to download these files, you can use one of the options shown in the Docs.
Please note that in order to use this method, you must opt-in to version 2 of Security Rules, which can be done by making rules_version = '2'; the first line of your security rules:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
first , you should get the file download Url to retrieve it, the easiest way is to upload a file and generate the download Url in your database, so after that you just go and retrieve each file from the storage like this :
private void downloadFile() {
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReferenceFromUrl("<your_bucket>");
StorageReference islandRef = storageRef.child("file.txt");
File rootPath = new File(Environment.getExternalStorageDirectory(), "file_name");
if(!rootPath.exists()) {
rootPath.mkdirs();
}
final File localFile = new File(rootPath,"imageName.txt");
islandRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Log.e("firebase ",";local tem file created created " +localFile.toString());
// updateDb(timestamp,localFile.toString(),position);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Log.e("firebase ",";local tem file not created created " +exception.toString());
}
});
}
I personally use this method, whenever you upload a file, save its download URL in your Firebase Database, if you are uploading multiple files then save it in an array. There is no method for Firebase Storage android to download and upload multiple files in one go.
Whenever you want to download files access your firebase database for those URL's.
I am adding images for all user in storage section, below is my code for uploading images.
public void uploadImage(byte[] data, final String fileName) {
mProgressDialog.setMessage("Uploading image....");
mProgressDialog.show();
StorageReference filepath=mStorageRef.child("Photos").child(fileName);
filepath.putBytes(data).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mProgressDialog.dismiss();
String mUrl=taskSnapshot.getDownloadUrl().toString();
// got url for this image what to do with this url.....
Toast.makeText(MainActivity1.this,"Upload done!",Toast.LENGTH_LONG).show();
}
});
}
I want to obtain all images url stored for a particular user.
There is no API for listing items of Firebase Storage on the client side.
You should modify your file upload method to also store that download URL somewhere in the user's control, like a user-specific path in the Realtime Database.