Java Code Examples for com.google.firebase.storage.StorageReference#child()

The following examples show how to use com.google.firebase.storage.StorageReference#child() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FirebaseStorageHelper.java    From NaviBee with GNU General Public License v3.0 6 votes vote down vote up
public static File loadImageWithFile(String filePath, boolean isThumb) {

        if (isThumb) {
            int where = filePath.lastIndexOf(".");
            filePath = filePath.substring(0, where) + "-thumb" + filePath.substring(where);
        }

        // fs- is for firebase storage caches
        String filename = "fs-"+ sha256(filePath);
        File file = new File(NaviBeeApplication.getInstance().getCacheDir(), filename);

        if (file.exists()) {
            return file;
        } else {
            // cache not exists
            FirebaseStorage storage = FirebaseStorage.getInstance();
            StorageReference storageRef = storage.getReference();
            storageRef = storageRef.child(filePath);
            storageRef.getFile(file).addOnSuccessListener(taskSnapshot -> {
                // Local temp file has been created
                Bitmap b = loadImageFromCacheFile(file);
            }).addOnFailureListener(taskSnapshot -> {
            });
            return file;
        }
    }
 
Example 2
Source File: StorageActivity.java    From snippets-android with Apache License 2.0 6 votes vote down vote up
public void includesForDeleteFiles() {
    FirebaseStorage storage = FirebaseStorage.getInstance();

    // [START delete_file]
    // Create a storage reference from our app
    StorageReference storageRef = storage.getReference();

    // Create a reference to the file to delete
    StorageReference desertRef = storageRef.child("images/desert.jpg");

    // Delete the file
    desertRef.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
            // File deleted successfully
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception exception) {
            // Uh-oh, an error occurred!
        }
    });
    // [END delete_file]
}
 
Example 3
Source File: FirebaseStorageHelper.java    From NaviBee with GNU General Public License v3.0 5 votes vote down vote up
public static void loadImage(ImageView imageView, String filePath, boolean isThumb, Callback callback) {
    final String tag = filePath;
    imageView.setTag(tag);

    if (isThumb) {
        int where = filePath.lastIndexOf(".");
        filePath = filePath.substring(0, where) + "-thumb" + filePath.substring(where);
    }

    // fs- is for firebase storage caches
    String filename = "fs-"+ sha256(filePath);
    File file = new File(NaviBeeApplication.getInstance().getCacheDir(), filename);

    if (file.exists()) {
        // cache exists
        loadImageFromCacheFile(imageView, file, tag);
        if (callback != null) callback.callback(true);
    } else {
        // cache not exists

        FirebaseStorage storage = FirebaseStorage.getInstance();
        StorageReference storageRef = storage.getReference();
        storageRef = storageRef.child(filePath);
        storageRef.getFile(file).addOnSuccessListener(taskSnapshot -> {
            // Local temp file has been created
            loadImageFromCacheFile(imageView, file, tag);
            if (callback != null) callback.callback(true);
        }).addOnFailureListener(taskSnapshot -> {
            if (callback != null) callback.callback(false);
        });

    }
}
 
Example 4
Source File: FirebaseStorageHelper.java    From NaviBee with GNU General Public License v3.0 5 votes vote down vote up
public static void loadImage(String filePath, boolean isThumb, FileCallback callback) {

        if (isThumb) {
            int where = filePath.lastIndexOf(".");
            filePath = filePath.substring(0, where) + "-thumb" + filePath.substring(where);
        }

        // fs- is for firebase storage caches
        String filename = "fs-"+ sha256(filePath);
        File file = new File(NaviBeeApplication.getInstance().getCacheDir(), filename);

        if (file.exists()) {
            // cache exists
            if (callback != null) callback.callback(true, file);
        } else {
            // cache not exists
            FirebaseStorage storage = FirebaseStorage.getInstance();
            StorageReference storageRef = storage.getReference();
            storageRef = storageRef.child(filePath);
            storageRef.getFile(file).addOnSuccessListener(taskSnapshot -> {
                // Local temp file has been created
                if (callback != null) callback.callback(true, file);
            }).addOnFailureListener(taskSnapshot -> {
                if (callback != null) callback.callback(false, null);
            });

        }
    }
 
Example 5
Source File: StorageActivity.java    From snippets-android with Apache License 2.0 5 votes vote down vote up
public void includesForMetadata_delete() {
    FirebaseStorage storage = FirebaseStorage.getInstance();
    StorageReference storageRef = storage.getReference();
    StorageReference forestRef = storageRef.child("images/forest.jpg");

    // [START delete_file_metadata]
    // Create file metadata with property to delete
    StorageMetadata metadata = new StorageMetadata.Builder()
            .setContentType(null)
            .build();

    // Delete the metadata property
    forestRef.updateMetadata(metadata)
            .addOnSuccessListener(new OnSuccessListener<StorageMetadata>() {
                @Override
                public void onSuccess(StorageMetadata storageMetadata) {
                    // metadata.contentType should be null
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception exception) {
                    // Uh-oh, an error occurred!
                }
            });
    // [END delete_file_metadata]
}
 
Example 6
Source File: FirebaseStorageHelper.java    From NaviBee with GNU General Public License v3.0 4 votes vote down vote up
public static void uploadImage(Uri uri, String uploadName, String category,
          int compressQuality, boolean thumbOnly, UploadCallback callback) throws IOException {


    // storage reference
    FirebaseStorage storage = FirebaseStorage.getInstance();
    StorageReference storageRef = storage.getReference();
    storageRef = storageRef.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child(category);

    if (uploadName==null) {
        uploadName = UUID.randomUUID().toString();
    }

    StorageReference storageRefOri = storageRef.child(uploadName + ".jpg");
    StorageReference storageRefThumb = storageRef.child(uploadName + "-thumb.jpg");

    String fullFilename = storageRefOri.getPath();




    ArrayList<UploadTask> tasks = new ArrayList<>();


    if (!thumbOnly) {
        // image
        byte[] bo = scaleImage(uri, IMAGE_SIZE, compressQuality);
        tasks.add(storageRefOri.putBytes(bo));
    }

    // thumb
    byte[] bt = scaleImage(uri, THUMB_IMAGE_SIZE, compressQuality);
    tasks.add(storageRefThumb.putBytes(bt));

    AtomicBoolean failed = new AtomicBoolean(false);

    for (UploadTask task : tasks) {
        task.addOnCompleteListener(result -> {
            if (failed.get()) return;

            if (result.isSuccessful()) {
                tasks.remove(task);
                if (tasks.isEmpty()) {
                    callback.callback(true, fullFilename);
                }
            } else {
                failed.set(true);
                for (UploadTask t:tasks) {
                    if (t!=task) {
                        t.cancel();
                    }
                }
                callback.callback(false, "");
            }
        });
    }
}
 
Example 7
Source File: SaveReports.java    From Crimson with Apache License 2.0 4 votes vote down vote up
private void uploadReport() {

        progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("Uploading");
        progressDialog.setMessage("Please wait...");
        progressDialog.setIndeterminate(true);
        progressDialog.show();


        FirebaseStorage storage = FirebaseStorage.getInstance();
        StorageReference storageRef = storage.getReferenceFromUrl("gs://crimsonnew-33e2c.appspot.com");

        final String uuid = UUID.randomUUID().toString();

        String name= "reports/test"+uuid+".jpg";

        spaceRef = storageRef.child(name);

        imageView.setDrawingCacheEnabled(true);
        imageView.buildDrawingCache();
        Bitmap bitmap = imageView.getDrawingCache();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] data = baos.toByteArray();

        UploadTask uploadTask = spaceRef.putBytes(data);
        uploadTask.addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception exception) {
                // Handle unsuccessful uploads

                progressDialog.dismiss();
                Toast.makeText(SaveReports.this,"Failed to upload.",Toast.LENGTH_SHORT).show();

            }
        }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                // taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
                Uri downloadUrl = taskSnapshot.getDownloadUrl();

                reportsRef.child(uuid).setValue(downloadUrl.toString());
                imageView.refreshDrawableState();

                progressDialog.dismiss();
                Toast.makeText(SaveReports.this,"Uploaded successfully.",Toast.LENGTH_SHORT).show();
                imageView.refreshDrawableState();

            }
        });


    }
 
Example 8
Source File: StorageActivity.java    From snippets-android with Apache License 2.0 4 votes vote down vote up
public void includesForCreateReference() {
    FirebaseStorage storage = FirebaseStorage.getInstance();

    // ## Create a Reference

    // [START create_storage_reference]
    // Create a storage reference from our app
    StorageReference storageRef = storage.getReference();
    // [END create_storage_reference]

    // [START create_child_reference]
    // Create a child reference
    // imagesRef now points to "images"
    StorageReference imagesRef = storageRef.child("images");

    // Child references can also take paths
    // spaceRef now points to "images/space.jpg
    // imagesRef still points to "images"
    StorageReference spaceRef = storageRef.child("images/space.jpg");
    // [END create_child_reference]

    // ## Navigate with References

    // [START navigate_references]
    // getParent allows us to move our reference to a parent node
    // imagesRef now points to 'images'
    imagesRef = spaceRef.getParent();

    // getRoot allows us to move all the way back to the top of our bucket
    // rootRef now points to the root
    StorageReference rootRef = spaceRef.getRoot();
    // [END navigate_references]

    // [START chain_navigation]
    // References can be chained together multiple times
    // earthRef points to 'images/earth.jpg'
    StorageReference earthRef = spaceRef.getParent().child("earth.jpg");

    // nullRef is null, since the parent of root is null
    StorageReference nullRef = spaceRef.getRoot().getParent();
    // [END chain_navigation]

    // ## Reference Properties

    // [START reference_properties]
    // Reference's path is: "images/space.jpg"
    // This is analogous to a file path on disk
    spaceRef.getPath();

    // Reference's name is the last segment of the full path: "space.jpg"
    // This is analogous to the file name
    spaceRef.getName();

    // Reference's bucket is the name of the storage bucket that the files are stored in
    spaceRef.getBucket();
    // [END reference_properties]

    // ## Full Example

    // [START reference_full_example]
    // Points to the root reference
    storageRef = storage.getReference();

    // Points to "images"
    imagesRef = storageRef.child("images");

    // Points to "images/space.jpg"
    // Note that you can use variables to create child values
    String fileName = "space.jpg";
    spaceRef = imagesRef.child(fileName);

    // File path is "images/space.jpg"
    String path = spaceRef.getPath();

    // File name is "space.jpg"
    String name = spaceRef.getName();

    // Points to "images"
    imagesRef = spaceRef.getParent();
    // [END reference_full_example]
}
 
Example 9
Source File: MainActivity.java    From stockita-point-of-sale with MIT License 4 votes vote down vote up
/**
 * Helper method to save and upload images to the server
 */
private void saveImageIntoRealDatabaseAndStorage(String realFilePath) {


    /**
     * Add the {@link ItemImageModel} to the server
     */

    // Instantiate the model pass file path and push key as argument
    ItemImageModel itemImageModel = new ItemImageModel(realFilePath, aaItemMasterPushKey);

    // Initialize the server location for real time database
    DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference()
            .child(aaItemMasterUserUid)
            .child(Constants.FIREBASE_ITEM_MASTER_IMAGE_LOCATION)
            .child(aaItemMasterPushKey);

    // Set the value with push() so each itemMaster can have multiple itemImage
    databaseReference.push().setValue(itemImageModel);

    /**
     * Now upload the file to the cloud
     */

    // Initialize storage
    mImageStorageRef = FirebaseStorage.getInstance().getReference();

    // Get reference to the specific storage location to storage the images
    StorageReference imageStorageRefForUser =
            mImageStorageRef
                    .child(aaItemMasterUserUid)
                    .child(Constants.FIREBASE_ITEM_MASTER_IMAGE_LOCATION)
                    .child(aaItemMasterPushKey);

    // Get the imagePath from the model then convert imagePath to Uri
    Uri file = Uri.fromFile(new File(itemImageModel.getImageUrl()));

    // Pack the Uri object into StorageReference object
    StorageReference uriRef = imageStorageRefForUser.child(file.getLastPathSegment());

    // Create & add file metadata including the content type
    StorageMetadata metadata = new StorageMetadata.Builder()
            .setContentType("image/jpg")
            .build();

    // Upload the file, pass the Uri file and the metadata as argument
    UploadTask uploadTask = uriRef.putFile(file, metadata);

    // Register observers to listen for when the upload is done or if it fails
    uploadTask.addOnFailureListener(this, new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {

        }
    }).addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onSuccess(@NonNull UploadTask.TaskSnapshot taskSnapshot) {
            //Uri downloadUrl = taskSnapshot.getDownloadUrl();

        }
    });

}