com.google.firebase.storage.StorageReference Java Examples

The following examples show how to use com.google.firebase.storage.StorageReference. 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: ImageUtil.java    From social-app-android with 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 #2
Source File: BookmarksActivity.java    From SimplicityBrowser with 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 #3
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 #4
Source File: Storage.java    From gdx-fireapp with 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 #5
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 #6
Source File: MainActivity.java    From SimplicityBrowser with 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 #7
Source File: ProfileActivity.java    From SnapchatClone with 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 #8
Source File: StorageTest.java    From firebase-android-sdk with 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 #9
Source File: MainActivity.java    From Shipr-Community-Android with GNU General Public License v3.0 6 votes vote down vote up
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 #10
Source File: SampleActivity.java    From RxFirebase with 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 #11
Source File: StorageTest.java    From firebase-android-sdk with 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 #12
Source File: DoorbellEntryAdapter.java    From doorbell with Apache License 2.0 5 votes vote down vote up
@Override
protected void onBindViewHolder(DoorbellEntryViewHolder holder, int position, DoorbellEntry model) {
    // Display the timestamp
    CharSequence prettyTime = DateUtils.getRelativeDateTimeString(mApplicationContext,
            model.getTimestamp(), DateUtils.SECOND_IN_MILLIS, DateUtils.WEEK_IN_MILLIS, 0);
    holder.time.setText(prettyTime);

    // Display the image
    if (model.getImage() != null) {
        StorageReference imageRef = mFirebaseStorage.getReferenceFromUrl(model.getImage());

        GlideApp.with(mApplicationContext)
                .load(imageRef)
                .placeholder(R.drawable.ic_image)
                .into(holder.image);
    }

    // Display the metadata
    if (model.getAnnotations() != null) {
        ArrayList<String> keywords = new ArrayList<>(model.getAnnotations().keySet());

        int limit = Math.min(keywords.size(), 3);
        holder.metadata.setText(TextUtils.join("\n", keywords.subList(0, limit)));
    } else {
        holder.metadata.setText("no annotations yet");
    }
}
 
Example #13
Source File: RxFirebaseStorage.java    From RxFirebase with Apache License 2.0 5 votes vote down vote up
@NonNull
public static Observable<UploadTask.TaskSnapshot> putBytes(@NonNull final StorageReference storageRef,
                                                           @NonNull final byte[] bytes,
                                                           @NonNull final StorageMetadata metadata) {
    return Observable.unsafeCreate(new Observable.OnSubscribe<UploadTask.TaskSnapshot>() {
        @Override
        public void call(final Subscriber<? super UploadTask.TaskSnapshot> subscriber) {
            RxTask.assignOnTask(subscriber, storageRef.putBytes(bytes, metadata));
        }
    });
}
 
Example #14
Source File: RxFirebaseStorage.java    From RxFirebase with Apache License 2.0 5 votes vote down vote up
@NonNull
public static Observable<UploadTask.TaskSnapshot> putStream(@NonNull final StorageReference storageRef,
                                                            @NonNull final InputStream stream,
                                                            @NonNull final StorageMetadata metadata) {
    return Observable.unsafeCreate(new Observable.OnSubscribe<UploadTask.TaskSnapshot>() {
        @Override
        public void call(final Subscriber<? super UploadTask.TaskSnapshot> subscriber) {
            RxTask.assignOnTask(subscriber, storageRef.putStream(stream, metadata));
        }
    });
}
 
Example #15
Source File: SampleActivity.java    From RxFirebase with Apache License 2.0 5 votes vote down vote up
private void uploadFile(StorageReference storageRef) {
    File targetFile = null;
    try {
        targetFile = File.createTempFile("tmp", "rx");
    } catch (IOException e) {
        e.printStackTrace();
    }
    RxFirebaseStorage.getFile(storageRef.child("README.md"), targetFile)
            .subscribe(snapshot -> {
                Log.i("rxFirebaseSample", "transferred: " + snapshot.getBytesTransferred() + " bytes");
            }, throwable -> {
                Log.e("rxFirebaseSample", throwable.toString());
            });
}
 
Example #16
Source File: RxFirebaseStorage.java    From RxFirebase with Apache License 2.0 5 votes vote down vote up
@NonNull
public static Observable<UploadTask.TaskSnapshot> putFile(@NonNull final StorageReference storageRef,
                                                          @NonNull final Uri uri) {
    return Observable.unsafeCreate(new Observable.OnSubscribe<UploadTask.TaskSnapshot>() {
        @Override
        public void call(final Subscriber<? super UploadTask.TaskSnapshot> subscriber) {
            RxTask.assignOnTask(subscriber, storageRef.putFile(uri));
        }
    });
}
 
Example #17
Source File: NewSimplicityAccount.java    From SimplicityBrowser with MIT License 5 votes vote down vote up
@SuppressWarnings("StatementWithEmptyBody")
private void uploadToFireBase(){
    try{
        StorageReference proimage = FirebaseStorage.getInstance().getReference(currentUser.getUid() +"/profilepicture/"+currentUser.getUid()+ ".jpg");
        if(user_pic != null){
            proimage.putFile(user_pic).continueWithTask(task -> {
                        if (!task.isSuccessful()) {
                            throw Objects.requireNonNull(task.getException());
                        }
                        return proimage.getDownloadUrl();
                    }).addOnCompleteListener(task -> {
                        if (task.isSuccessful()) {
                            Uri downloadUri = task.getResult();
                            if (downloadUri != null) {
                                pic_url = downloadUri.toString();
                            }
                            Cardbar.snackBar(getApplicationContext(),"Uploaded profile image.", true).show();
                            createUserFile();
                        } else {
                            Cardbar.snackBar(getApplicationContext(), Objects.requireNonNull(task.getException()).toString(), true).show();

                        }
                    });


        }

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

    }
}
 
Example #18
Source File: RxFirebaseStorage.java    From RxFirebase with Apache License 2.0 5 votes vote down vote up
@NonNull
public static Observable<StorageMetadata> updateMetadata(@NonNull final StorageReference storageRef,
                                                         @NonNull final StorageMetadata metadata) {
    return Observable.unsafeCreate(new Observable.OnSubscribe<StorageMetadata>() {
        @Override
        public void call(final Subscriber<? super StorageMetadata> subscriber) {
            RxTask.assignOnTask(subscriber, storageRef.updateMetadata(metadata));
        }
    });
}
 
Example #19
Source File: RxFirebaseStorage.java    From RxFirebase with Apache License 2.0 5 votes vote down vote up
@NonNull
public static Observable<Void> delete(@NonNull final StorageReference storageRef) {
    return Observable.unsafeCreate(new Observable.OnSubscribe<Void>() {
        @Override
        public void call(final Subscriber<? super Void> subscriber) {
            RxTask.assignOnTask(subscriber, storageRef.delete());
        }
    });
}
 
Example #20
Source File: RxFirebaseStorage.java    From rxfirebase with Apache License 2.0 5 votes vote down vote up
/**
 * @see StorageReference#delete()
 */
@CheckReturnValue
@NonNull
public static Completable delete(@NonNull final StorageReference ref) {
    return RxTask.completes(new Callable<Task<Void>>() {
        @Override
        public Task<Void> call() throws Exception {
            return ref.delete();
        }
    });
}
 
Example #21
Source File: RxFirebaseStorage.java    From rxfirebase with Apache License 2.0 5 votes vote down vote up
/**
 * @see StorageReference#putFile(Uri, StorageMetadata)
 */
@CheckReturnValue
@NonNull
public static Single<UploadTask.TaskSnapshot> putFile(
        @NonNull final StorageReference ref,
        @NonNull final Uri uri,
        @NonNull final StorageMetadata storageMetadata) {
    return RxTask.single(new Callable<Task<UploadTask.TaskSnapshot>>() {
        @Override
        public Task<UploadTask.TaskSnapshot> call() throws Exception {
            return ref.putFile(uri, storageMetadata);
        }
    });
}
 
Example #22
Source File: FirebaseRequestHandler.java    From android-instant-apps-demo with Apache License 2.0 5 votes vote down vote up
@Override
public Result load(Request request, int networkPolicy) throws IOException {
    Log.i(TAG, "load " + request.uri.toString());
    StorageReference gsReference = firebaseStorage.getReferenceFromUrl(request.uri.toString());
    StreamDownloadTask mStreamTask = gsReference.getStream();

    InputStream inputStream;
    try {
        inputStream = Tasks.await(mStreamTask).getStream();
        return new Result(BitmapFactory.decodeStream(inputStream), Picasso.LoadedFrom.NETWORK);
    } catch (ExecutionException | InterruptedException e) {
        throw new IOException(e);
    }
}
 
Example #23
Source File: MyAppGlideModule.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
@Override
public void registerComponents(@NonNull Context context,
                               @NonNull Glide glide,
                               @NonNull Registry registry) {
    // Register FirebaseImageLoader to handle StorageReference
    registry.append(StorageReference.class, InputStream.class,
            new FirebaseImageLoader.Factory());
}
 
Example #24
Source File: StorageActivity.java    From snippets-android with Apache License 2.0 5 votes vote down vote up
public void listAllPaginated(@Nullable String pageToken) {
    FirebaseStorage storage = FirebaseStorage.getInstance();
    StorageReference listRef = storage.getReference().child("files/uid");

    // Fetch the next page of results, using the pageToken if we have one.
    Task<ListResult> listPageTask = pageToken != null
            ? listRef.list(100, pageToken)
            : listRef.list(100);

    listPageTask
            .addOnSuccessListener(new OnSuccessListener<ListResult>() {
                @Override
                public void onSuccess(ListResult listResult) {
                    List<StorageReference> prefixes = listResult.getPrefixes();
                    List<StorageReference> items = listResult.getItems();

                    // Process page of results
                    // ...

                    // Recurse onto next page
                    if (listResult.getPageToken() != null) {
                        listAllPaginated(listResult.getPageToken());
                    }
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    // Uh-oh, an error occurred.
                }
            });
}
 
Example #25
Source File: StorageActivity.java    From snippets-android with Apache License 2.0 5 votes vote down vote up
public void listAllFiles() {
    FirebaseStorage storage = FirebaseStorage.getInstance();
    // [START storage_list_all]
    StorageReference listRef = storage.getReference().child("files/uid");

    listRef.listAll()
            .addOnSuccessListener(new OnSuccessListener<ListResult>() {
                @Override
                public void onSuccess(ListResult listResult) {
                    for (StorageReference prefix : listResult.getPrefixes()) {
                        // All the prefixes under listRef.
                        // You may call listAll() recursively on them.
                    }

                    for (StorageReference item : listResult.getItems()) {
                        // All the items under listRef.
                    }
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    // Uh-oh, an error occurred!
                }
            });
    // [END storage_list_all]
}
 
Example #26
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 #27
Source File: GcsDownloadHelper.java    From firebase-android-client with Apache License 2.0 5 votes vote down vote up
private void getGcsDownloadUri(String gcsUrl, OnCompleteListener<Uri> getDownloadUriListener)
        throws IllegalArgumentException {
    // [START gcs_download_uri]
    FirebaseStorage storage = FirebaseStorage.getInstance();
    StorageReference gsReference = storage.getReferenceFromUrl(gcsUrl);
    gsReference.getDownloadUrl().addOnCompleteListener(getDownloadUriListener);
    // [END gcs_download_uri]
}
 
Example #28
Source File: ImageUtil.java    From social-app-android with Apache License 2.0 5 votes vote down vote up
public static void loadImageWithSimpleTarget(GlideRequests glideRequests, StorageReference imageStorageRef, SimpleTarget<Bitmap> simpleTarget) {
    glideRequests.asBitmap()
            .load(imageStorageRef)
            .diskCacheStrategy(DiskCacheStrategy.ALL)
            .fitCenter()
            .into(simpleTarget);
}
 
Example #29
Source File: ImageUtil.java    From social-app-android with Apache License 2.0 5 votes vote down vote up
public static void loadImageCenterCrop(GlideRequests glideRequests, StorageReference imageStorageRef, ImageView imageView,
                                       RequestListener<Drawable> listener) {
    glideRequests.load(imageStorageRef)
            .centerCrop()
            .diskCacheStrategy(DiskCacheStrategy.ALL)
            .error(R.drawable.ic_stub)
            .listener(listener)
            .into(imageView);
}
 
Example #30
Source File: RxFirebaseStorage.java    From RxFirebase with Apache License 2.0 5 votes vote down vote up
@NonNull
public static Observable<Uri> getDownloadUrl(@NonNull final StorageReference storageRef) {
    return Observable.unsafeCreate(new Observable.OnSubscribe<Uri>() {
        @Override
        public void call(final Subscriber<? super Uri> subscriber) {
            RxTask.assignOnTask(subscriber, storageRef.getDownloadUrl());
        }
    });
}