Search in sources :

Example 16 with UploadTask

use of com.google.firebase.storage.UploadTask in project MadMax by deviz92.

the class FirebaseUtils method addPendingExpenseFirebase.

public void addPendingExpenseFirebase(Expense expense, ImageView expensePhoto, Context context) {
    Log.d(TAG, "addPendingExpenseFirebase");
    // Aggiungo pending expense a Firebase
    final String eID = databaseReference.child("proposedExpenses").push().getKey();
    databaseReference.child("proposedExpenses").child(eID).setValue(expense);
    StorageReference uExpensePhotoFilenameRef = storageReference.child("proposedExpenses").child(eID).child(eID + "_expensePhoto.jpg");
    if (expensePhoto != null) {
        Bitmap bitmap;
        expensePhoto.setDrawingCacheEnabled(true);
        expensePhoto.buildDrawingCache();
        bitmap = expensePhoto.getDrawingCache();
        // Get the data from an ImageView as bytes
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] data = baos.toByteArray();
        UploadTask uploadTask = uExpensePhotoFilenameRef.putBytes(data);
        uploadTask.addOnFailureListener(new OnFailureListener() {

            @Override
            public void onFailure(@NonNull Exception exception) {
                // todo Handle unsuccessful uploads
                Log.e(TAG, "image upload failed");
            }
        }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {

            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                // taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
                databaseReference.child("proposedExpenses").child(eID).child("expensePhoto").setValue(taskSnapshot.getMetadata().getDownloadUrl().toString());
            }
        });
    }
    Log.d(TAG, "creator expense " + expense.getCreatorID());
    // e aggiungo spesa alla lista spese di ogni participant
    for (Map.Entry<String, Double> participant : expense.getParticipants().entrySet()) {
        Log.d(TAG, "participant " + participant.getKey());
        // Setto voto nel participant a null
        databaseReference.child("proposedExpenses").child(eID).child("participants").child(participant.getKey()).child("vote").setValue("null");
        // Aggiungo campo deleted al participant
        databaseReference.child("proposedExpenses").child(eID).child("participants").child(participant.getKey()).child("deleted").setValue(false);
        // Aggiungo spesaID a elenco spese pending dello user
        databaseReference.child("users").child(participant.getKey()).child("proposedExpenses").child(eID).setValue(true);
    }
    // Aggiungo spesa pending alla lista spese pending del gruppo
    databaseReference.child("groups").child(expense.getGroupID()).child("proposedExpenses").push();
    databaseReference.child("groups").child(expense.getGroupID()).child("proposedExpenses").child(eID).setValue(true);
}
Also used : StorageReference(com.google.firebase.storage.StorageReference) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Bitmap(android.graphics.Bitmap) UploadTask(com.google.firebase.storage.UploadTask) NonNull(android.support.annotation.NonNull) HashMap(java.util.HashMap) Map(java.util.Map) TreeMap(java.util.TreeMap) OnFailureListener(com.google.android.gms.tasks.OnFailureListener)

Example 17 with UploadTask

use of com.google.firebase.storage.UploadTask in project ARD by MobileApplicationsClub.

the class SendDocumentService method uploadDocument.

/**
 * Method to upload document to firebase and prepare its url.
 *
 * @param data        Uri to save on firebase.
 * @param otherUserId receiver's id.
 * @param messageId   parent message id.
 * @param documentId  document id to use.
 */
private void uploadDocument(Uri data, String otherUserId, String messageId, String documentId) {
    StorageReference sRef = getStorageRef().child(getUser().getUid()).child(otherUserId).child(documentId);
    UploadTask uploadTask = sRef.putFile(data);
    // Register observers to listen for when the download is done or if it fails
    uploadTask.addOnFailureListener(exception -> {
        // Handle unsuccessful uploads
        Toast.makeText(this, "Upload failed. Will try again later", Toast.LENGTH_SHORT).show();
    }).addOnSuccessListener(taskSnapshot -> {
        // and download URL.
        if (data.toString().contains("image")) {
            StorageReference tRef = sRef.getParent().child("thumbs").child(documentId);
            InputStream image_stream;
            try {
                image_stream = getContentResolver().openInputStream(data);
                Bitmap bitmap = BitmapFactory.decodeStream(image_stream);
                bitmap = Bitmap.createScaledBitmap(bitmap, Math.min(200, bitmap.getWidth()), Math.min(200, bitmap.getHeight()), false);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                byte[] byteData = baos.toByteArray();
                UploadTask uploadThumbTask = tRef.putBytes(byteData);
                uploadThumbTask.addOnCompleteListener(task -> {
                    Toast.makeText(SendDocumentService.this, "Document uploaded on server. Sending to user", Toast.LENGTH_SHORT).show();
                    Uri downloadUrl = taskSnapshot.getMetadata().getDownloadUrl();
                    updateDocumentRemoteUrl(downloadUrl.toString(), task.getResult().getDownloadUrl().toString(), messageId);
                });
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                Toast.makeText(this, "Try again later", Toast.LENGTH_SHORT).show();
            }
        }
    }).addOnProgressListener(taskSnapshot -> {
        if (taskSnapshot.getBytesTransferred() != 0)
            Toast.makeText(SendDocumentService.this, taskSnapshot.getBytesTransferred() / 1000 + " Kbytes uploaded", Toast.LENGTH_SHORT).show();
    });
}
Also used : MessageStatusType(com.macbitsgoa.ard.types.MessageStatusType) ByteArrayOutputStream(java.io.ByteArrayOutputStream) RealmList(io.realm.RealmList) Uri(android.net.Uri) DatabaseReference(com.google.firebase.database.DatabaseReference) Intent(android.content.Intent) BitmapFactory(android.graphics.BitmapFactory) HashMap(java.util.HashMap) MessageItemKeys(com.macbitsgoa.ard.keys.MessageItemKeys) Calendar(java.util.Calendar) Toast(android.widget.Toast) ChatItemKeys(com.macbitsgoa.ard.keys.ChatItemKeys) Map(java.util.Map) ChatsItem(com.macbitsgoa.ard.models.ChatsItem) AHC(com.macbitsgoa.ard.utils.AHC) Log(android.util.Log) Realm(io.realm.Realm) DocumentItemKeys(com.macbitsgoa.ard.keys.DocumentItemKeys) FileNotFoundException(java.io.FileNotFoundException) MessageItem(com.macbitsgoa.ard.models.MessageItem) Bitmap(android.graphics.Bitmap) StorageReference(com.google.firebase.storage.StorageReference) Sort(io.realm.Sort) DocumentItem(com.macbitsgoa.ard.models.DocumentItem) UploadTask(com.google.firebase.storage.UploadTask) InputStream(java.io.InputStream) UploadTask(com.google.firebase.storage.UploadTask) Bitmap(android.graphics.Bitmap) StorageReference(com.google.firebase.storage.StorageReference) InputStream(java.io.InputStream) FileNotFoundException(java.io.FileNotFoundException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Uri(android.net.Uri)

Example 18 with UploadTask

use of com.google.firebase.storage.UploadTask in project Lets-Chat by kshitiz1007.

the class SettingActivity method onActivityResult.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // -----STARTING GALLERY----
    if (requestCode == GALLERY_PICK && resultCode == RESULT_OK) {
        Uri sourceUri = data.getData();
        // -------CROPPING IMAGE AND SETTING MINIMUM SIZE TO 500 , 500------
        CropImage.activity(sourceUri).setAspectRatio(1, 1).setMinCropWindowSize(500, 500).start(SettingActivity.this);
    }
    // ------START CROP IMAGE ACTIVITY------
    if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
        // ------CROP IMAGE RESULT------
        CropImage.ActivityResult result = CropImage.getActivityResult(data);
        if (resultCode == RESULT_OK) {
            mProgressDialog.setTitle("Uploading Image");
            mProgressDialog.setMessage("Please wait while we process and upload the image...");
            mProgressDialog.setCancelable(false);
            mProgressDialog.setProgress(ProgressDialog.STYLE_SPINNER);
            mProgressDialog.show();
            Uri resultUri = result.getUri();
            File thumb_filepath = new File(resultUri.getPath());
            try {
                // --------COMPRESSING IMAGE--------
                Bitmap thumb_bitmap = new Compressor(this).setMaxWidth(200).setMaxHeight(200).setQuality(75).compressToBitmap(thumb_filepath);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                thumb_bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                thumb_bytes = baos.toByteArray();
            } catch (IOException e) {
                e.printStackTrace();
            }
            StorageReference filepath = mStorageReference.child("profile_image").child(uid + ".jpg");
            final StorageReference thumb_file_path = mStorageReference.child("profile_image").child("thumbs").child(uid + ".jpg");
            // ------STORING IMAGE IN FIREBASE STORAGE--------
            filepath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {

                @Override
                public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
                    if (task.isSuccessful()) {
                        @SuppressWarnings("VisibleForTests") final String downloadUrl = task.getResult().getDownloadUrl().toString();
                        UploadTask uploadTask = thumb_file_path.putBytes(thumb_bytes);
                        // ---------- STORING THUMB IMAGE INTO STORAGE REFERENCE --------
                        uploadTask.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {

                            @Override
                            public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> thumb_task) {
                                @SuppressWarnings("VisibleForTests") String thumb_download_url = thumb_task.getResult().getDownloadUrl().toString();
                                if (thumb_task.isSuccessful()) {
                                    Map update_HashMap = new HashMap();
                                    update_HashMap.put("image", downloadUrl);
                                    update_HashMap.put("thumb_image", thumb_download_url);
                                    // --------ADDING URL INTO DATABASE REFERENCE--------
                                    mDatabaseReference.updateChildren(update_HashMap).addOnCompleteListener(new OnCompleteListener<Void>() {

                                        @Override
                                        public void onComplete(@NonNull Task<Void> task) {
                                            if (task.isSuccessful()) {
                                                mProgressDialog.dismiss();
                                                Toast.makeText(SettingActivity.this, "Uploaded Successfuly...", Toast.LENGTH_SHORT).show();
                                            } else {
                                                mProgressDialog.dismiss();
                                                Toast.makeText(getApplicationContext(), " Image is not uploading...", Toast.LENGTH_SHORT).show();
                                            }
                                        }
                                    });
                                } else {
                                    mProgressDialog.dismiss();
                                    Toast.makeText(getApplicationContext(), " Error in uploading Thumbnail..", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                    } else {
                        mProgressDialog.dismiss();
                        Toast.makeText(getApplicationContext(), " Image is not uploading...", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
            Exception error = result.getError();
        }
    }
}
Also used : Task(com.google.android.gms.tasks.Task) UploadTask(com.google.firebase.storage.UploadTask) HashMap(java.util.HashMap) Uri(android.net.Uri) CropImage(com.theartofdev.edmodo.cropper.CropImage) Bitmap(android.graphics.Bitmap) UploadTask(com.google.firebase.storage.UploadTask) NonNull(android.support.annotation.NonNull) StorageReference(com.google.firebase.storage.StorageReference) Compressor(id.zelory.compressor.Compressor) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) IOException(java.io.IOException) OnCompleteListener(com.google.android.gms.tasks.OnCompleteListener) File(java.io.File) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

UploadTask (com.google.firebase.storage.UploadTask)18 NonNull (android.support.annotation.NonNull)15 OnFailureListener (com.google.android.gms.tasks.OnFailureListener)14 ByteArrayOutputStream (java.io.ByteArrayOutputStream)14 StorageReference (com.google.firebase.storage.StorageReference)13 Bitmap (android.graphics.Bitmap)12 HashMap (java.util.HashMap)8 IOException (java.io.IOException)7 Intent (android.content.Intent)6 Map (java.util.Map)6 SimpleDateFormat (java.text.SimpleDateFormat)5 Uri (android.net.Uri)4 OnCompleteListener (com.google.android.gms.tasks.OnCompleteListener)4 Task (com.google.android.gms.tasks.Task)4 FirebaseUser (com.google.firebase.auth.FirebaseUser)4 User (com.polito.mad17.madmax.entities.User)4 TreeMap (java.util.TreeMap)4 View (android.view.View)3 Compressor (id.zelory.compressor.Compressor)3 File (java.io.File)3