android Firebase Appliaction Stopped - android

when i run my application to upload an image from an external storage to firebase cloud storage application has been stopped after pressing the upload button.
FS = FirebaseStorage.getInstance();
Ref = FS.getReference("Record_Unknown/");
Updata = (Button)findViewById(R.id.Updata_btn);
Updata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
InputStream inputStream = null;
try {
inputStream = new FileInputStream(new File(getFilesDir(),"view-of-mountain-under-blue-sky-2104147.jpg"));
}catch (FileNotFoundException e)
{
e.printStackTrace();
}
UploadTask uploadTask = Ref.child("Images/view-of-mountain-under-blue-sky-2104147.jpg").putStream(inputStream);
final InputStream finalInputStream = inputStream;
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
if (finalInputStream !=null){
try {
finalInputStream.close();
}
catch (IOException e){
e.printStackTrace();
}
}
Toast.makeText(MainActivity.this, "Uploaded Sucessfully", Toast.LENGTH_SHORT).show();
}
});
}
});}
line no.94 is given below:
inputStream = new FileInputStream(new File(getFilesDir(),"view-of-mountain-under-blue-sky-2104147.jpg"));
line no.100 is given below:
UploadTask uploadTask = Ref.child("Images/view-of-mountain-under-blue-sky-2104147.jpg").putStream(inputStream);

As the exception you show says the file you are trying to load does not exist.
The getFilesDir() in android returns the application storage directory which is private to your application (and not visible to a file browser on the device). If you are trying to access the shared part of the file system you need:
a) Priviledges
b) To use another call to get the relevant part of the file system
Android docs summarise the available areas here https://developer.android.com/training/data-storage

Related

How to download file from Firebase storage to custom folder?

I have been searching all day long even here on stack overflow but none of the code seems to work. I want to download a file(s) from FirebaseStorage to a custom folder on internal/external storage but no luck whatsoever.
my code:
private void downloadfile() {
mStorageRef = FirebaseStorage.getInstance().getReference();
ref = mStorageRef.child("song.mp3");
try {
File localFile = File.createTempFile("song", "mp3");
} catch (IOException e) {
e.printStackTrace();
}
File storagePath = new File(Environment.getExternalStorageDirectory(), "My Folder");
// Create direcorty if not exists
if(!storagePath.exists()) {
storagePath.mkdirs();
}
final File myFile = new File(storagePath,"song.mp3");
mStorageRef.getFile(myFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
// Local temp file has been created
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
}
});
}
1.) Create the path to the file
String sdcardPath = Environment.getExternalStorageDirectory().toString();
String filePath = sdCardPath + "<YOUR_PATH_LIKE_/Downloads>" + "Filename";
2.) Create the file:
File directory = new File(filePath);

How to download file into internal downloads folder in Android

I am pretty new with this, and I could use some help.
I am having difficulties downloading files from firebase storage into my android device storage. Problem is that files are downloaded into cache memory of app, and I would like to use them when I'm offline. Other thing is that I am not using SD card, so I would like my files downloaded into some of user accessible folder, if possible into download folder in internal memory.
Here is my code:
StorageReference ref = storage.getReferenceFromUrl("gs://diplomskirad-948a7.appspot.com/Dennis Lloyd - NEVERMIND.mp3");
File localFile=null;
try {
localFile = File.createTempFile("audio", ".mp3");
} catch (IOException e) {
e.printStackTrace();
}
ref.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Log.d("Success", "File downloaded successfully");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Log.e("Error", "Error downloading file");
}
});
I guess should somehow change my "onSuccess" method, but I didn't have any success until now.
Try this:-
StorageReference ref = storage.getReferenceFromUrl("gs://diplomskirad-948a7.appspot.com/Dennis Lloyd - NEVERMIND.mp3");
File path= new File(Environment.getExternalStorageDirectory(), "file_name");
if(!path.exists()) {
path.mkdirs();
}
final File localFile = new File(path,"audio.mp3");
ref.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Log.d("Success", "File downloaded successfully " + localFile.toString());
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Log.e("Error", "Error downloading file");
}
});

Download audios from Firebase (Android Studio)

people of StackOverflow.
Recently I finish a course of Android Studio andd in classes we begin to work with Firebase. I managed that my application reproduce audios in mp3 from the database, but now I would like to share it in another application, for it, I have done this:
this.stRef = FirebaseStorage.getInstance().getReference().child("audios/audioname.mp3");
File localFile = null;
String downloadedaudio="";
try {
localFile = File.createTempFile("audioname", ".mp3");
downloadedaudio = localFile.getPath();
} catch (IOException e) {
e.printStackTrace();
}
stRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(getContext(),"Downloaded",Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Toast.makeText(getContext(),"Failed to Download"+exception,Toast.LENGTH_LONG).show();
}
});
The app download a temp file, i check it in Android Studio file explorer, but then i does not share anything:
Uri uri = Uri.parse(downloadedaudio);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("audio/mp3");
share.putExtra(Intent.EXTRA_STREAM,uri);
c.startActivity(Intent.createChooser(share, "Compartir sonido en: "));
}
Any idea of what i am doing wrong?
Thank you.

How to download file using url stored inside firebase database?

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.

In Android, where does the file downloaded from Firebase storage get stored?

I uploaded a file to Firebase Storage from my project console. Now, I downloaded that file from my app using the method 'Download to a local file' as mentioned in the Firebase Storage documentation, but I am not able to find the downloaded file on my phone.
Can someone tell me where does that file get downloaded to?
FirebaseStorage firebaseStorage = FirebaseStorage.getInstance();
final StorageReference storageReference = firebaseStorage.getReferenceFromUrl("gs://ldq-app-d2e6b.appspot.com");
button_down.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String fileName = new String(editText_file.getText().toString());
StorageReference childReference = storageReference.child("Quizzes");
StorageReference fileReference = storageReference.child("Quizzes/" + fileName + ".pdf");
File localFile = null;
try {
localFile = File.createTempFile(fileName, "pdf");
}
catch (IOException ioe){
Toast.makeText(getContext(), "File creation failed", Toast.LENGTH_SHORT).show();
}
fileReference.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(getContext(),"File downloaded",LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getContext(),"Download failed. Try again!", LENGTH_SHORT).show();
}
});
//Toast.makeText(getContext(),"Button working",LENGTH_SHORT).show();
}
});
As per Firebase Document, they are creating a temporary file for saving Image from Url. Link
File localFile = File.createTempFile("images", "jpg");
If you want to store it on phone's internal memory or in external memory then just create a File with storage path and pass it to FileDownloadTask.
File storagePath = new File(Environment.getExternalStorageDirectory(), "directory_name");
// Create direcorty if not exists
if(!storagePath.exists()) {
storagePath.mkdirs();
}
final File myFile = new File(storagePath,"file_name");
yourStorageRef.getFile(myFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
// Local temp file has been created
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
}
});

Categories

Resources