Java Code Examples for com.google.firebase.storage.FirebaseStorage#getInstance()

The following examples show how to use com.google.firebase.storage.FirebaseStorage#getInstance() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
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 8
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 9
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 10
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 11
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 12
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 13
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 14
Source File: addPatientActivity.java    From Doctorave with MIT License 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_patient);
    setTitle("Add Patient");

    patientName = findViewById(R.id.patientName);
    patientphno = findViewById(R.id.patientphno);
    patientEmail =  findViewById(R.id.patientEmail);
    patientDob= findViewById(R.id.patientDob);
    patientAdd = findViewById(R.id.patientAdd);
    patientPic = findViewById(R.id.patientPic);
    radioGroup = findViewById(R.id.radioGroup);

    connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

    patientPic.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            //Checking the Network State
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            if(networkInfo == null){
                Toast.makeText(addPatientActivity.this, "Please Connect to Internet to use this feature", Toast.LENGTH_SHORT).show();
            }else {
                Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                    startActivityForResult(takePictureIntent, RC_PHOTO_PICKER);
                }
            }
        }
    });

    user = doctorPreference.getUsernameFromSP(this);
    doctorPushId = doctorPreference.getUserPushId(this);

    mFirebaseStorage = FirebaseStorage.getInstance();
    mStorageReference = mFirebaseStorage.getReference().child("doctor_app").child(doctorPushId).child(charUtility.filterString(user));

    mFirebaseDatabase = FirebaseDatabase.getInstance();
    mDatabaseReference = mFirebaseDatabase.getReference().child(doctorPushId).child(charUtility.filterString(user)).child("patientData");

    patientUri = getIntent().getStringExtra("patientUri");

    String fullname = getIntent().getStringExtra("fullname");
    String phoneno = getIntent().getStringExtra("phoneno");
    String dob = getIntent().getStringExtra("dob");
    String email = getIntent().getStringExtra("email");
    String address = getIntent().getStringExtra("address");

    if(fullname != null){
        addPatientFromAppointment(fullname, phoneno, dob, email, address);
    }


    if(patientUri != null){
        getLoaderManager().initLoader(EDIT_LOADER, null, this);
    }
}
 
Example 15
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 16
Source File: Storage.java    From gdx-fireapp with Apache License 2.0 4 votes vote down vote up
/**
 * @return Lazy loaded instance of {@link FirebaseStorage}. It should be only one instance for one instance of {@link Storage}
 */
private FirebaseStorage firebaseStorage() {
    if (firebaseStorage == null)
        firebaseStorage = FirebaseStorage.getInstance();
    return firebaseStorage;
}
 
Example 17
Source File: DriverHome.java    From UberClone with MIT License 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_drawer_home);
    verifyGoogleAccount();
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    firebaseStorage=FirebaseStorage.getInstance();
    storageReference=firebaseStorage.getReference();



    location=new Location(this, new locationListener() {
        @Override
        public void locationResponse(LocationResult response) {
            // Add a icon_marker in Sydney and move the camera
            Common.currentLat=response.getLastLocation().getLatitude();
            Common.currentLng=response.getLastLocation().getLongitude();
            displayLocation();
        }
    });

    locationSwitch=findViewById(R.id.locationSwitch);
    locationSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            if (b){
                FirebaseDatabase.getInstance().goOnline();
                location.inicializeLocation();
                drivers= FirebaseDatabase.getInstance().getReference(Common.driver_tbl).child(Common.currentUser.getCarType());
                geoFire=new GeoFire(drivers);
            }else{
                FirebaseDatabase.getInstance().goOffline();
                location.stopUpdateLocation();
                currentLocationMarket.remove();
                mMap.clear();
                //handler.removeCallbacks(drawPathRunnable);
                if (currentLocationMarket!=null)currentLocationMarket.remove();
            }
        }
    });
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    setUpLocation();
    updateFirebaseToken();
}
 
Example 18
Source File: StorageActivity.java    From snippets-android with Apache License 2.0 4 votes vote down vote up
public void nonDefaultBucket() {
    // [START storage_non_default_bucket]
    // Get a non-default Storage bucket
    FirebaseStorage storage = FirebaseStorage.getInstance("gs://my-custom-bucket");
    // [END storage_non_default_bucket]
}
 
Example 19
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 20
Source File: UserListingRecyclerAdapter.java    From FirebaseMessagingApp with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
    final User user = mUsers.get(position);

    String alphabet;

    //  holder.txtLastMessage.setText(user.email);
    try {
        holder.txtUsername.setText(user.nameAndSurname);
        alphabet = user.nameAndSurname.substring(0, 1);
    } catch (Exception e) {
        holder.txtUsername.setText(user.email);
        alphabet = user.email.substring(0, 1);
    }

    //  holder.txtUserAlphabet.setText(alphabet);

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

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

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

        }
    });


}