Java Code Examples for com.google.firebase.storage.StorageReference

The following examples show how to use com.google.firebase.storage.StorageReference. These examples are extracted from open source projects. 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 Project: SnapchatClone   Source File: ProfileActivity.java    License: MIT License 6 votes vote down vote up
private void saveProfileImage() {
    if (newProfileImageUrl != null) {
        if (!currentProfileImageUrl.equals("default")) {
            StorageReference photoDelete = FirebaseStorage.getInstance().getReferenceFromUrl(currentProfileImageUrl);

            photoDelete.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void aVoid) {
                    uploadImage();
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    saveProfileImage();
                }
            });
        } else {
            uploadImage();
        }
    } else {
        saveProfile();
    }
}
 
Example 2
private void uploadImageToStorage(StorageReference photoRef, Uri selectedImageUri) {

        UploadTask uploadTask = photoRef.putFile(selectedImageUri);

        Task<Uri> urlTask = uploadTask.continueWithTask(task -> {
            if (!task.isSuccessful()) {
                throw Objects.requireNonNull(task.getException());
            }

            // Continue with the task to get the download URL
            return photoRef.getDownloadUrl();
        }).addOnCompleteListener(task -> {
            if (task.isSuccessful()) {

                downloadUri = task.getResult();
                updateProfilePic(downloadUri);
            }  // Handle failures
            // ...

        });

    }
 
Example 3
Source Project: firebase-android-sdk   Source File: StorageTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void putShouldFailWithNotAuthorized() throws Exception {
  FirebaseAuth auth = FirebaseAuth.getInstance();
  FirebaseStorage storage = FirebaseStorage.getInstance();

  auth.signOut();
  StorageReference blob = storage.getReference("restaurants").child(TestId.create());
  byte[] data = "Google NYC".getBytes(StandardCharsets.UTF_8);

  try {
    Task<?> putTask = blob.putBytes(Arrays.copyOf(data, data.length));
    Throwable failure = Tasks2.waitForFailure(putTask);
    StorageException ex = (StorageException) failure;
    assertThat(ex.getErrorCode()).isEqualTo(StorageException.ERROR_NOT_AUTHORIZED);
  } finally {
    Tasks2.waitBestEffort(blob.delete());
  }
}
 
Example 4
Source Project: firebase-android-sdk   Source File: StorageTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void getShouldReturnNewlyPutData() throws Exception {
  FirebaseAuth auth = FirebaseAuth.getInstance();
  FirebaseStorage storage = FirebaseStorage.getInstance();

  auth.signOut();
  Task<?> signInTask = auth.signInWithEmailAndPassword("[email protected]", "password");
  Tasks2.waitForSuccess(signInTask);

  StorageReference blob = storage.getReference("restaurants").child(TestId.create());

  byte[] data = "Google NYC".getBytes(StandardCharsets.UTF_8);

  try {
    Task<?> putTask = blob.putBytes(Arrays.copyOf(data, data.length));
    Tasks2.waitForSuccess(putTask);

    Task<byte[]> getTask = blob.getBytes(128);
    Tasks2.waitForSuccess(getTask);

    byte[] result = getTask.getResult();
    assertThat(result).isEqualTo(data);
  } finally {
    Tasks2.waitBestEffort(blob.delete());
  }
}
 
Example 5
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 6
Source Project: gdx-fireapp   Source File: Storage.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Promise<Void> delete(final String path) {
    return FuturePromise.when(new Consumer<FuturePromise<Void>>() {
        @Override
        public void accept(final FuturePromise<Void> voidFuturePromise) {
            StorageReference pathRef = firebaseStorage().getReference().child(path);
            pathRef.delete().addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    voidFuturePromise.doFail(e);
                }
            }).addOnSuccessListener(new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void aVoid) {
                    voidFuturePromise.doComplete(null);
                }
            });
        }
    });
}
 
Example 7
Source Project: social-app-android   Source File: ImageUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static void loadMediumImageCenterCrop(GlideRequests glideRequests,
                                             StorageReference imageStorageRefMedium,
                                             StorageReference imageStorageRefOriginal,
                                             ImageView imageView,
                                             int width,
                                             int height,
                                             RequestListener<Drawable> listener) {

    glideRequests.load(imageStorageRefMedium)
            .centerCrop()
            .override(width, height)
            .diskCacheStrategy(DiskCacheStrategy.ALL)
            .error(R.drawable.ic_stub)
            .listener(listener)
            .error(glideRequests.load(imageStorageRefOriginal))
            .into(imageView);
}
 
Example 8
Source Project: SimplicityBrowser   Source File: BookmarksActivity.java    License: MIT License 6 votes vote down vote up
private void downloadFromFirebase(){
    try{
        StorageReference proimage = FirebaseStorage.getInstance().getReference(currentUser.getUid() +"/simplicity_backup/"+ currentUser.getUid() + ".sbh");
        File bh = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + File.separator + getResources().getString(R.string.app_name) + File.separator + "Simplicity Backups" + File.separator, currentUser.getUid() + ".sbh");
        ExportUtils.readFromFile(bh, this);
        proimage.getFile(bh).addOnSuccessListener(taskSnapshot -> {
            Log.d("Downloaded", "got backup from Firebase");
            adapterBookmarks.notifyDataSetChanged();
        }).addOnFailureListener(exception ->
                Log.d("Failed from Firebase", Objects.requireNonNull(exception).toString()));

    }catch (NullPointerException i){
        i.printStackTrace();
    }catch (Exception ignored){

    }
}
 
Example 9
Source Project: snippets-android   Source File: StorageActivity.java    License: 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 10
Source Project: SimplicityBrowser   Source File: MainActivity.java    License: MIT License 6 votes vote down vote up
private void downloadFromFirebase(){
    try{
    StorageReference proimage = FirebaseStorage.getInstance().getReference(currentUser.getUid() +"/simplicity_backup/"+ currentUser.getUid() + ".sbh");
    File bh = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + File.separator + getResources().getString(R.string.app_name) + File.separator + "Simplicity Backups" + File.separator, currentUser.getUid() + ".sbh");

    proimage.getFile(bh).addOnSuccessListener(taskSnapshot -> {
        Log.d("Downloaded", "got backup from Firebase");
        ExportUtils.readFromFile(bh, this);
    }).addOnFailureListener(exception ->
            Log.d("Failed from Firebase", Objects.requireNonNull(exception).toString()));

    }catch (NullPointerException i){
        i.printStackTrace();
    }catch (Exception ignored){

    }
}
 
Example 11
Source Project: RxFirebase   Source File: SampleActivity.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sample);

    final TextView postsTextView = (TextView) findViewById(R.id.txtPosts);
    final TextView userTextView = (TextView) findViewById(R.id.txtUsers);

    authenticate();

    DatabaseReference reference = FirebaseDatabase.getInstance().getReference();

    getBlogPostsAsList(postsTextView, reference);
    getBlogPostsAsMap(postsTextView, reference);

    getUser(userTextView, reference);
    getNonExistedUser(userTextView, reference);
    getUserCustomMapper(userTextView, reference);

    StorageReference storageRef = FirebaseStorage.getInstance().getReference();
    downloadFile(storageRef);
    uploadFile(storageRef);

    uploadImage(storageRef);
    downloadImage(storageRef);
}
 
Example 12
Source Project: SimplicityBrowser   Source File: MainActivity.java    License: MIT License 5 votes vote down vote up
private void uploadToFireBase(){
    try{
        if(currentUser != null) {
            final File root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            String pathToMyAttachedFile = File.separator + getResources().getString(R.string.app_name) + File.separator + "Simplicity Backups" + File.separator + mAuth.getCurrentUser().getUid() + ".sbh";
            File file = new File(root, pathToMyAttachedFile);
            final Uri uri = Uri.fromFile(file);
            StorageReference proimage = FirebaseStorage.getInstance().getReference(mAuth.getCurrentUser().getUid() + "/simplicity_backup/" + mAuth.getCurrentUser().getUid() + ".sbh");
            if (uri != null) {
                proimage.putFile(uri).continueWithTask(task -> {
                    if (!task.isSuccessful()) {
                        throw Objects.requireNonNull(task.getException());
                    }
                    return proimage.getDownloadUrl();
                }).addOnCompleteListener(task -> {
                    if (task.isSuccessful()) {
                        ExportUtils.writeToFile(file, this);
                        Log.d("Backed up", "sent history to Firebase");
                    } else {
                        Log.d("Failed backed up", Objects.requireNonNull(task.getException()).toString());
                    }
                });


            }
        }

    }catch (NullPointerException i){
        i.printStackTrace();
    }catch (Exception ignored){

    }
}
 
Example 13
Source Project: social-app-android   Source File: DatabaseHelper.java    License: Apache License 2.0 5 votes vote down vote up
public UploadTask uploadImage(Uri uri, String imageTitle) {
    StorageReference riversRef = getStorageReference().child(IMAGES_STORAGE_KEY + "/" + imageTitle);
    // Create file metadata including the content type
    StorageMetadata metadata = new StorageMetadata.Builder()
            .setCacheControl("max-age=7776000, Expires=7776000, public, must-revalidate")
            .build();

    return riversRef.putFile(uri, metadata);
}
 
Example 14
Source Project: rxfirebase   Source File: RxFirebaseStorage.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @see StorageReference#putStream(InputStream, StorageMetadata)
 */
@CheckReturnValue
@NonNull
public static Single<UploadTask.TaskSnapshot> putStream(
        @NonNull final StorageReference ref,
        @NonNull final InputStream inputStream,
        @NonNull final StorageMetadata storageMetadata) {
    return RxTask.single(new Callable<Task<UploadTask.TaskSnapshot>>() {
        @Override
        public Task<UploadTask.TaskSnapshot> call() throws Exception {
            return ref.putStream(inputStream, storageMetadata);
        }
    });
}
 
Example 15
Source Project: rxfirebase   Source File: RxFirebaseStorage.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @see StorageReference#updateMetadata(StorageMetadata)
 */
@CheckReturnValue
@NonNull
public static Single<StorageMetadata> updateMetadata(
        @NonNull final StorageReference ref,
        @NonNull final StorageMetadata storageMetadata) {
    return RxTask.single(new Callable<Task<StorageMetadata>>() {
        @Override
        public Task<StorageMetadata> call() throws Exception {
            return ref.updateMetadata(storageMetadata);
        }
    });
}
 
Example 16
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 17
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 18
Source Project: FirebaseUI-Android   Source File: FirebaseImageLoader.java    License: Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public LoadData<InputStream> buildLoadData(@NonNull StorageReference reference,
                                           int height,
                                           int width,
                                           @NonNull Options options) {
    return new LoadData<>(
            new FirebaseStorageKey(reference),
            new FirebaseStorageFetcher(reference));
}
 
Example 19
Source Project: CloudFunctionsExample   Source File: MainActivity.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onActivityResult(int requestCode,int resultCode, Intent data) {
    super.onActivityResult(requestCode,resultCode,data);
    if(requestCode == RC_SIGN_IN) {
        if(resultCode == RESULT_OK) {
            Toast.makeText(this, "Signed in.", Toast.LENGTH_SHORT).show();
        }
        else if(resultCode == RESULT_CANCELED) {
            Toast.makeText(this, "Sign in canceled.", Toast.LENGTH_SHORT).show();
            finish();
        }
    }
    else if(requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK) {
        Uri selectedImageUri = data.getData();
        StorageReference photoRef =
                mChatPhotosStorageRef.child(selectedImageUri.getLastPathSegment());

        photoRef.putFile(selectedImageUri)
                .addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        Uri downloadUrl = taskSnapshot.getDownloadUrl();
                        Message message = new Message(null, mUsername, downloadUrl.toString());
                        mMessagesReference.push().setValue(message);
                    }
                });
    }
}
 
Example 20
Source Project: codelab-friendlychat-android   Source File: MainActivity.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Log.d(TAG, "onActivityResult: requestCode=" + requestCode + ", resultCode=" + resultCode);

    if (requestCode == REQUEST_IMAGE) {
        if (resultCode == RESULT_OK) {
            if (data != null) {
                final Uri uri = data.getData();
                Log.d(TAG, "Uri: " + uri.toString());

                FriendlyMessage tempMessage = new FriendlyMessage(null, mUsername, mPhotoUrl,
                        LOADING_IMAGE_URL);
                mFirebaseDatabaseReference.child(MESSAGES_CHILD).push()
                        .setValue(tempMessage, new DatabaseReference.CompletionListener() {
                            @Override
                            public void onComplete(DatabaseError databaseError,
                                                   DatabaseReference databaseReference) {
                                if (databaseError == null) {
                                    String key = databaseReference.getKey();
                                    StorageReference storageReference =
                                            FirebaseStorage.getInstance()
                                                    .getReference(mFirebaseUser.getUid())
                                                    .child(key)
                                                    .child(uri.getLastPathSegment());

                                    putImageInStorage(storageReference, uri, key);
                                } else {
                                    Log.w(TAG, "Unable to write message to database.",
                                            databaseError.toException());
                                }
                            }
                        });
            }
        }
    }
}
 
Example 21
Source Project: rxfirebase   Source File: RxFirebaseStorage.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @see StorageReference#getFile(File)
 */
@CheckReturnValue
@NonNull
public static Single<FileDownloadTask.TaskSnapshot> getFile(@NonNull final StorageReference ref,
                                                            @NonNull final File file) {
    return RxTask.single(new Callable<Task<FileDownloadTask.TaskSnapshot>>() {
        @Override
        public Task<FileDownloadTask.TaskSnapshot> call() throws Exception {
            return ref.getFile(file);
        }
    });
}
 
Example 22
Source Project: gdx-fireapp   Source File: DownloadProcessor.java    License: Apache License 2.0 5 votes vote down vote up
void processDownload(FirebaseStorage firebaseStorage, String path, long bytesLimit, final FuturePromise<byte[]> promise) {
    StorageReference pathRef = firebaseStorage.getReference().child(path);
    pathRef.getBytes(bytesLimit).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            promise.doFail(e);
        }
    }).addOnSuccessListener(new OnSuccessListener<byte[]>() {
        @Override
        public void onSuccess(byte[] bytes) {
            promise.doComplete(bytes);
        }
    });
}
 
Example 23
Source Project: gdx-fireapp   Source File: StorageTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void setup() throws Exception {
    super.setup();
    PowerMockito.mockStatic(FirebaseStorage.class);
    firebaseStorage = Mockito.mock(FirebaseStorage.class);
    storageReference = Mockito.mock(StorageReference.class);
    when(FirebaseStorage.getInstance()).thenReturn(firebaseStorage);
    when(firebaseStorage.getReference()).thenReturn(storageReference);
    when(firebaseStorage.getReference().child(Mockito.anyString())).thenReturn(storageReference);
    when(firebaseStorage.getReference(Mockito.nullable(String.class))).thenReturn(storageReference);
}
 
Example 24
Source Project: RxFirebase   Source File: SampleActivity.java    License: Apache License 2.0 5 votes vote down vote up
private void uploadImage(StorageReference storageRef) {
    Drawable res = getResources().getDrawable(R.drawable.ic_verified_user_black_18dp);
    Bitmap bitmap = ((BitmapDrawable) res).getBitmap();
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
    RxFirebaseStorage.putBytes(storageRef.child("image"), stream.toByteArray())
            .subscribe(url -> {
                Log.i("rxFirebaseSample", "url: " + url.toString());
            });
}
 
Example 25
Source Project: rxfirebase   Source File: RxFirebaseStorage.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @see StorageReference#getMetadata()
 */
@CheckReturnValue
@NonNull
public static Single<StorageMetadata> getMetadata(@NonNull final StorageReference ref) {
    return RxTask.single(new Callable<Task<StorageMetadata>>() {
        @Override
        public Task<StorageMetadata> call() throws Exception {
            return ref.getMetadata();
        }
    });
}
 
Example 26
Source Project: rxfirebase   Source File: RxFirebaseStorage.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @see StorageReference#getDownloadUrl()
 */
@CheckReturnValue
@NonNull
public static Single<Uri> getDownloadUrl(@NonNull final StorageReference ref) {
    return RxTask.single(new Callable<Task<Uri>>() {
        @Override
        public Task<Uri> call() throws Exception {
            return ref.getDownloadUrl();
        }
    });
}
 
Example 27
Source Project: rxfirebase   Source File: RxFirebaseStorage.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @see StorageReference#getBytes(long)
 */
@CheckReturnValue
@NonNull
public static Single<byte[]> getBytes(@NonNull final StorageReference ref,
                                      final long maxDownloadSizeBytes) {
    return RxTask.single(new Callable<Task<byte[]>>() {
        @Override
        public Task<byte[]> call() throws Exception {
            return ref.getBytes(maxDownloadSizeBytes);
        }
    });
}
 
Example 28
Source Project: social-app-android   Source File: DatabaseHelper.java    License: Apache License 2.0 5 votes vote down vote up
public UploadTask uploadImage(Uri uri, String imageTitle) {
    StorageReference riversRef = getStorageReference().child(IMAGES_STORAGE_KEY + "/" + imageTitle);
    // Create file metadata including the content type
    StorageMetadata metadata = new StorageMetadata.Builder()
            .setCacheControl("max-age=7776000, Expires=7776000, public, must-revalidate")
            .build();

    return riversRef.putFile(uri, metadata);
}
 
Example 29
Source Project: social-app-android   Source File: ImageUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static void loadImageCenterCrop(GlideRequests glideRequests, StorageReference imageStorageRef, ImageView imageView,
                                       int width, int height) {
    glideRequests.load(imageStorageRef)
            .centerCrop()
            .override(width, height)
            .diskCacheStrategy(DiskCacheStrategy.ALL)
            .error(R.drawable.ic_stub)
            .into(imageView);
}
 
Example 30
Source Project: social-app-android   Source File: ImageUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static void loadImageCenterCrop(GlideRequests glideRequests, StorageReference imageStorageRef, ImageView imageView,
                                       int width, int height, RequestListener<Drawable> listener) {
    glideRequests.load(imageStorageRef)
            .centerCrop()
            .override(width, height)
            .diskCacheStrategy(DiskCacheStrategy.ALL)
            .error(R.drawable.ic_stub)
            .listener(listener)
            .into(imageView);
}