Download a file from Firebase Storage from Android

0

I am developing an application in which I want to be able to download a JSON file from a server and then be consumed on the device locally (in order to feed certain activities with information).

This I do to be able to update the information remotely and thus be updated without the need to launch a new update with the new information in the Play Store.

I am currently using Firebase. Then I uploaded an file to Cloud Storage of it and I'm trying to download it. The code you use is the following:

private void downloadfile() {
    FirebaseStorage storage = FirebaseStorage.getInstance();
    StorageReference httpsReference = storage.getReferenceFromUrl("https://firebasestorage.googleapis.com/......");

    File localFile = null;
    try {
        localFile = File.createTempFile("dishes", "json");
    } catch (IOException e) 
    {
        e.printStackTrace();
    }

    httpsReference.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
        @Override
        public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) 
        {
            Toast.makeText(MainActivity.this, "Se descargo bien", Toast.LENGTH_SHORT).show();
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception exception) {
            Toast.makeText(MainActivity.this, "Error al descragar", Toast.LENGTH_SHORT).show();
        }
    });
}

The code will take it out of the official documentation of Firebase. link

According to this, the file is downloaded, but I can not find it anywhere. What is the error? Or how can I locate my file?

PD: I use the .getAbsolutePath () to show me where I "save", but the route it shows does not exist.

File localFile = null;
Utilio el metodo localFile.getAbsolutePath();
    
asked by Alan Oliver 31.05.2018 в 04:50
source

2 answers

0

Good morning, I work with firebase at work and we use it a lot, I tell you how it works, if you upload a json file from your computer the reference will have to be unique to the file and the reference will have to be by storage , which if you then need to update that json automatically, you will not be able to since the childEventListener that has a database will not notice when the file changes in the storage since it does not change anything in the database.

What do I suggest?

Upload the json file from the phone with firebase, generate the downloadURL and put it in your database with setValue, in this way you will always be able to access the location of your file

It is enough just to download the file with getFile and then unzip it to a directory to be able to read it later

I leave you a hint of how I upload a json from android to firebase

public Boolean subirJson(final DatabaseReference mDatabase, StorageReference mStorageRef)
    {
        Principal.Eljson().GuardarJson(Principal.getMiJson(), "ejemplo.txt");

        final StorageReference referenciaJson = mStorageRef;
        try {
            ejemplo = mContext.openFileInput("ejemplo.txt");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        referenciaJson.putStream(ejemplo).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                @SuppressWarnings("VisibleForTests") Uri downloadUrl = taskSnapshot.getDownloadUrl();

                mDatabase.setValue(downloadUrl.toString(), new DatabaseReference.CompletionListener() {
                    @Override
                    public void onComplete(DatabaseError databaseError, DatabaseReference referenciaJson) {
                        if(referenciaJson!=null){

                            Log.d("TAG", "Se guardo correctamente url");
                        }else{
                            Log.d("TAG", "Error al subir url");
                        }
                    }
                });


            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {

            }
        });
        return  false;
    }

To obtain them is more or less the same process

    mDatabase.child("Usuario").child(mAuth.getCurrentUser().getUid()).child("URL_Archivos").addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {

                                Log.e("Descarga","Existen Datos");

                                //Creamos donde se van a guardar los archivos, en este caso en cache momentaneo
                                File rootPath = new File(mContext.getCacheDir(),"Archivos);
                                if(!rootPath.exists()) {
                                    rootPath.mkdirs();//si no existe el directorio lo creamos
                                }
    mStorageRef = FirebaseStorage.getInstance().getReference().child("Archivos").child("Json").child("ejemplo" + mAuth.getCurrentUser().getEmail() + "txt");

                                final File jsonActualizado = new File(rootPath, "ejemplo.txt");


                                mStorageRef.getFile(jsonActualizado).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
                                    @Override
                                    public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {




                                    }
                                }).addOnFailureListener(new OnFailureListener() {
                                    @Override
                                    public void onFailure(@NonNull Exception e) {

                                    }
 }
 }

I hope you get the information!

    
answered by 31.05.2018 в 15:42
0

It would be much simpler to upload the file data to Cloud Firestore (firebase database), and then consume them normally, it's heavier for your application (it consumes more bandwidth) to have to download a file and then consume data from this, in addition to the ease of Firebase is to let it handle the entire Backend and consume the data directly, you could, in Node, put a trigger that skips tcada you upload the file, this is responsible for passing the data to CloudFirestore and then the application using conventional methods consumes this data already updated.

    
answered by 31.05.2018 в 15:58