com.google.firebase.storage.FirebaseStorage Java Examples

The following examples show how to use com.google.firebase.storage.FirebaseStorage. 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: 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 #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: 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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
Source File: StorageTest.java    From gdx-fireapp with 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 #10
Source File: StorageTest.java    From gdx-fireapp with Apache License 2.0 5 votes vote down vote up
@Test
public void inBucket() {
    // Given
    Storage storage = new Storage();

    // When
    storage.inBucket("test");

    // Then
    PowerMockito.verifyStatic(FirebaseStorage.class, VerificationModeFactory.times(1));
    FirebaseStorage.getInstance(Mockito.eq("test"));
}
 
Example #11
Source File: FirebaseUIActivity.java    From snippets-android with Apache License 2.0 5 votes vote down vote up
public void loadWithGlide() {
    // [START storage_load_with_glide]
    // Reference to an image file in Cloud Storage
    StorageReference storageReference = FirebaseStorage.getInstance().getReference();

    // ImageView in your Activity
    ImageView imageView = findViewById(R.id.imageView);

    // Download directly from StorageReference using Glide
    // (See MyAppGlideModule for Loader registration)
    Glide.with(this /* context */)
            .load(storageReference)
            .into(imageView);
    // [END storage_load_with_glide]
}
 
Example #12
Source File: NewSimplicityAccount.java    From SimplicityBrowser with MIT License 5 votes vote down vote up
@SuppressWarnings("StatementWithEmptyBody")
private void createUserFile(){
    try{
        final File root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        String pathToMyAttachedFile = File.separator + getResources().getString(R.string.app_name) + File.separator + "Simplicity Backups" + File.separator+ currentUser.getUid() + ".sbh";
        File file = new File(root, pathToMyAttachedFile);
        final Uri uri = Uri.fromFile(file);
        StorageReference proimage = FirebaseStorage.getInstance().getReference(currentUser.getUid() +"/simplicity_backup/"+currentUser.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()) {
                    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 File: DatabaseHelper.java    From social-app-android with Apache License 2.0 5 votes vote down vote up
public void init() {
        database = FirebaseDatabase.getInstance();
        database.setPersistenceEnabled(true);
        storage = FirebaseStorage.getInstance();

//        Sets the maximum time to retry upload operations if a failure occurs.
        storage.setMaxUploadRetryTimeMillis(Constants.Database.MAX_UPLOAD_RETRY_MILLIS);
    }
 
Example #14
Source File: DoorbellEntryAdapter.java    From doorbell with Apache License 2.0 5 votes vote down vote up
public DoorbellEntryAdapter(Context context, DatabaseReference ref) {
    super(new FirebaseRecyclerOptions.Builder<DoorbellEntry>()
            .setQuery(ref, DoorbellEntry.class)
            .build());

    mApplicationContext = context.getApplicationContext();
    mFirebaseStorage = FirebaseStorage.getInstance();
}
 
Example #15
Source File: HistoryActivity.java    From SimplicityBrowser with MIT License 5 votes vote down vote up
private void uploadToFireBase(){
    try{
        File bh = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + File.separator + getResources().getString(R.string.app_name) + File.separator + "Simplicity Backups" + File.separator);
        if (!bh.exists()) {
            //noinspection ResultOfMethodCallIgnored
            bh.mkdirs();
        }
        String extStorageDirectory = bh.toString();
        File file = new File(extStorageDirectory, currentUser.getUid() + ".sbh");
        ExportUtils.writeToFile(file, this);
        StorageReference proimage = FirebaseStorage.getInstance().getReference(currentUser.getUid() +"/simplicity_backup/"+currentUser.getUid() + ".sbh");
        if(Uri.fromFile(file) != null){
            proimage.putFile(Uri.fromFile(file)).continueWithTask(task -> {
                if (!task.isSuccessful()) {
                    throw Objects.requireNonNull(task.getException());
                }
                return proimage.getDownloadUrl();
            }).addOnCompleteListener(task -> {
                if (task.isSuccessful()) {
                    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 #16
Source File: ChatRecyclerAdapter.java    From FirebaseMessagingApp with GNU General Public License v3.0 5 votes vote down vote up
private void configureMyChatViewHolder(final MyChatViewHolder myChatViewHolder, int position) {
    final Chat chat = mChats.get(position);

    //String alphabet = chat.sender.substring(0, 1);

    myChatViewHolder.txtChatMessage.setText(chat.message);


    FirebaseStorage storage = FirebaseStorage.getInstance();
    StorageReference storageRef = storage.getReferenceFromUrl(context.getResources().getString(R.string.storage_link));
    storageRef.child("profilePictures/" + chat.sender + ".jpg").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
        @Override
        public void onSuccess(Uri uri) {

            try {
                Glide.with(myChatViewHolder.imgViewUser.getContext())
                        .load("" + uri.toString())
                        .diskCacheStrategy(DiskCacheStrategy.ALL) //use this to cache
                        .into(myChatViewHolder.imgViewUser);
            } catch (Exception ignored) {

            }
        }
    });

    myChatViewHolder.imgViewUser.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(myChatViewHolder.imgViewUser.getContext(), ProfileActivity.class);
            Bundle b = new Bundle();
            b.putString("key", chat.sender); //Your id
            intent.putExtras(b); //Put your id to your next Intent
            myChatViewHolder.imgViewUser.getContext().startActivity(intent);

        }
    });


    //   myChatViewHolder.imgViewUser.setText(alphabet);
}
 
Example #17
Source File: ChatRecyclerAdapter.java    From FirebaseMessagingApp with GNU General Public License v3.0 5 votes vote down vote up
private void configureOtherChatViewHolder(final OtherChatViewHolder otherChatViewHolder, int position) {
    final Chat chat = mChats.get(position);


    otherChatViewHolder.txtChatMessage.setText(chat.message);

    FirebaseStorage storage = FirebaseStorage.getInstance();
    StorageReference storageRef = storage.getReferenceFromUrl(context.getResources().getString(R.string.storage_link));
    storageRef.child("profilePictures/" + chat.sender + ".jpg").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
        @Override
        public void onSuccess(Uri uri) {

            try {
                Glide.with(otherChatViewHolder.imgViewUser.getContext())
                        .load("" + uri.toString())
                        .diskCacheStrategy(DiskCacheStrategy.ALL) //use this to cache
                        .into(otherChatViewHolder.imgViewUser);
            } catch (Exception ignored) {

            }
        }
    });
    otherChatViewHolder.imgViewUser.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(otherChatViewHolder.imgViewUser.getContext(), ProfileActivity.class);
            Bundle b = new Bundle();
            b.putString("key", chat.sender); //Your id
            intent.putExtras(b); //Put your id to your next Intent
            otherChatViewHolder.imgViewUser.getContext().startActivity(intent);

        }
    });
    //otherChatViewHolder.imgViewUser.setText(alphabet);
}
 
Example #18
Source File: SimplicityAccount.java    From SimplicityBrowser with MIT License 5 votes vote down vote up
private void downloadFromFirebase(){
    try{
        StorageReference proimage = FirebaseStorage.getInstance().getReference(Objects.requireNonNull(mAuth.getCurrentUser()).getUid() + "/simplicity_backup/" + mAuth.getCurrentUser().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, mAuth.getCurrentUser().getUid() + ".sbh");
        ExportUtils.readFromFile(bh, this);
        proimage.getFile(bh).addOnSuccessListener(taskSnapshot -> {
            Log.d("Downloaded", "got backup from Firebase");
        }).addOnFailureListener(exception ->
                Log.d("Failed from Firebase", Objects.requireNonNull(exception).toString()));
    }catch (NullPointerException i){
        i.printStackTrace();
    }catch (Exception ignored){

    }
}
 
Example #19
Source File: DoorbellActivity.java    From doorbell with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.d(TAG, "Doorbell Activity created.");

    // We need permission to access the camera
    if (checkSelfPermission(Manifest.permission.CAMERA)
            != PackageManager.PERMISSION_GRANTED) {
        // A problem occurred auto-granting the permission
        Log.e(TAG, "No permission");
        return;
    }

    mDatabase = FirebaseDatabase.getInstance();
    mStorage = FirebaseStorage.getInstance();

    // Creates new handlers and associated threads for camera and networking operations.
    mCameraThread = new HandlerThread("CameraBackground");
    mCameraThread.start();
    mCameraHandler = new Handler(mCameraThread.getLooper());

    mCloudThread = new HandlerThread("CloudThread");
    mCloudThread.start();
    mCloudHandler = new Handler(mCloudThread.getLooper());

    // Initialize the doorbell button driver
    initPIO();

    // Camera code is complicated, so we've shoved it all in this closet class for you.
    mCamera = DoorbellCamera.getInstance();
    mCamera.initializeCamera(this, mCameraHandler, mOnImageAvailableListener);
}
 
Example #20
Source File: MyDownloadService.java    From quickstart-android with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();

    // Initialize Storage
    mStorageRef = FirebaseStorage.getInstance().getReference();
}
 
Example #21
Source File: UploadProcessor.java    From gdx-fireapp with Apache License 2.0 5 votes vote down vote up
private void processUpload(final FirebaseStorage firebaseStorage, UploadTask uploadTask, final FuturePromise<FileMetadata> promise) {
    uploadTask.addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            promise.doFail(e);
        }
    }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
            FileMetadata fileMetadata = new FileMetadataBuilder(taskSnapshot, firebaseStorage).build();
            promise.doComplete(fileMetadata);
        }
    });
}
 
Example #22
Source File: StorageActivity.java    From snippets-android with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_storage);

    // [START storage_field_initialization]
    FirebaseStorage storage = FirebaseStorage.getInstance();
    // [END storage_field_initialization]

    includesForCreateReference();
}
 
Example #23
Source File: MyUploadService.java    From quickstart-android with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();

    // [START get_storage_ref]
    mStorageRef = FirebaseStorage.getInstance().getReference();
    // [END get_storage_ref]
}
 
Example #24
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 #25
Source File: PostActivity.java    From Simple-Blog-App with MIT License 5 votes vote down vote up
private void bindViews() {
    mprogressbar = new ProgressDialog(this);
    mDatabase = FirebaseDatabase.getInstance().getReference().child("Blog");
    mStorageRef = FirebaseStorage.getInstance().getReference();
    mPostTitle = (EditText) findViewById(R.id.editText1);
    mPostDesc = (EditText) findViewById(R.id.editText2);
    mSubmitBtn = (Button) findViewById(R.id.btn);
    mSelectImage = (ImageButton) findViewById(R.id.imageButton2);
}
 
Example #26
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 #27
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 #28
Source File: UploadActivity.java    From snippets-android with Apache License 2.0 5 votes vote down vote up
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);

    // If there was an upload in progress, get its reference and create a new StorageReference
    final String stringRef = savedInstanceState.getString("reference");
    if (stringRef == null) {
        return;
    }
    mStorageRef = FirebaseStorage.getInstance().getReferenceFromUrl(stringRef);

    // Find all UploadTasks under this StorageReference (in this example, there should be one)
    List<UploadTask> tasks = mStorageRef.getActiveUploadTasks();
    if (tasks.size() > 0) {
        // Get the task monitoring the upload
        UploadTask task = tasks.get(0);

        // Add new listeners to the task using an Activity scope
        task.addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot state) {
                // Success!
                // ...
            }
        });
    }
}
 
Example #29
Source File: DownloadActivity.java    From snippets-android with Apache License 2.0 5 votes vote down vote up
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);

    // If there was a download in progress, get its reference and create a new StorageReference
    final String stringRef = savedInstanceState.getString("reference");
    if (stringRef == null) {
        return;
    }
    mStorageRef = FirebaseStorage.getInstance().getReferenceFromUrl(stringRef);

    // Find all DownloadTasks under this StorageReference (in this example, there should be one)
    List<FileDownloadTask> tasks = mStorageRef.getActiveDownloadTasks();
    if (tasks.size() > 0) {
        // Get the task monitoring the download
        FileDownloadTask task = tasks.get(0);

        // Add new listeners to the task using an Activity scope
        task.addOnSuccessListener(this, new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(FileDownloadTask.TaskSnapshot state) {
                // Success!
                // ...
            }
        });
    }
}
 
Example #30
Source File: SetupActivity.java    From Simple-Blog-App with MIT License 5 votes vote down vote up
private void bindViews() {
    mAuth = FirebaseAuth.getInstance();
    mStorageRef = FirebaseStorage.getInstance().getReference().child("ProfileImages");
    mDatabseUsers = FirebaseDatabase.getInstance().getReference().child("Users");
    mSetupImage = (ImageButton) findViewById(R.id.setupImagebtn);
    mNameField = (EditText) findViewById(R.id.setupName);
    mFinishBtn = (Button) findViewById(R.id.finishbtn);
    mProgress = new ProgressDialog(this);
}