Search in sources :

Example 1 with UploadTask

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

the class FirebaseUtils method addExpenseFirebase.

public String addExpenseFirebase(final Expense expense, ImageView expensePhoto, ImageView billPhoto) {
    Log.d(TAG, "addExpenseFirebase");
    //Aggiungo spesa a Firebase
    final String eID = databaseReference.child("expenses").push().getKey();
    databaseReference.child("expenses").child(eID).setValue(expense);
    String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new java.util.Date());
    databaseReference.child("expenses").child(eID).child("timestamp").setValue(timeStamp);
    //databaseReference.child("expenses").child(eID).child("deleted").setValue(false);
    Bitmap bitmap;
    ByteArrayOutputStream baos;
    byte[] data;
    UploadTask uploadTask;
    // Get the data from an ImageView as bytes
    if (expensePhoto != null) {
        StorageReference uExpensePhotoFilenameRef = storageReference.child("expenses").child(eID).child(eID + "_expensePhoto.jpg");
        expensePhoto.setDrawingCacheEnabled(true);
        expensePhoto.buildDrawingCache();
        bitmap = expensePhoto.getDrawingCache();
        baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        data = baos.toByteArray();
        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("expenses").child(eID).child("expensePhoto").setValue(taskSnapshot.getMetadata().getDownloadUrl().toString());
            }
        });
    } else if (expense.getExpensePhoto() != null) {
        databaseReference.child("expenses").child(eID).child("expensePhoto").setValue(expense.getExpensePhoto());
    }
    if (billPhoto != null) {
        StorageReference uBillPhotoFilenameRef = storageReference.child("expenses").child(eID).child(eID + "_billPhoto.jpg");
        // Get the data from an ImageView as bytes
        billPhoto.setDrawingCacheEnabled(true);
        billPhoto.buildDrawingCache();
        bitmap = billPhoto.getDrawingCache();
        baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        data = baos.toByteArray();
        uploadTask = uBillPhotoFilenameRef.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("expenses").child(eID).child("billPhoto").setValue(taskSnapshot.getMetadata().getDownloadUrl().toString());
            }
        });
    } else if (expense.getBillPhoto() != null) {
        databaseReference.child("expenses").child(eID).child("billPhoto").setValue(expense.getBillPhoto());
    }
    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, "partecipant " + participant.getKey());
        //Se il participant corrente รจ il creatore della spesa
        if (participant.getKey().equals(expense.getCreatorID())) {
            //paga tutto lui
            databaseReference.child("expenses").child(eID).child("participants").child(participant.getKey()).child("alreadyPaid").setValue(expense.getAmount());
        } else {
            //gli altri participant inizialmente non pagano niente
            databaseReference.child("expenses").child(eID).child("participants").child(participant.getKey()).child("alreadyPaid").setValue(0);
        }
        //risetto fraction di spesa che deve pagare l'utente, visto che prima si sputtana
        databaseReference.child("expenses").child(eID).child("participants").child(participant.getKey()).child("fraction").setValue(expense.getParticipants().get(participant.getKey()));
        //Aggiungo spesaID a elenco spese dello user
        //todo controllare se utile
        databaseReference.child("users").child(participant.getKey()).child("expenses").child(eID).setValue(true);
    }
    //Aggiungo spesa alla lista spese del gruppo
    databaseReference.child("groups").child(expense.getGroupID()).child("expenses").push();
    databaseReference.child("groups").child(expense.getGroupID()).child("expenses").child(eID).setValue(true);
    return eID;
}
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) SimpleDateFormat(java.text.SimpleDateFormat) HashMap(java.util.HashMap) Map(java.util.Map) TreeMap(java.util.TreeMap) OnFailureListener(com.google.android.gms.tasks.OnFailureListener)

Example 2 with UploadTask

use of com.google.firebase.storage.UploadTask in project BORED by invent2017.

the class StoryUpload method uploadImage.

private void uploadImage(Uri file) {
    // String fileUri = file.toString();
    // File imageFile = new File(fileUri);
    StorageMetadata metadata = new StorageMetadata.Builder().setContentType("image/jpg").build();
    String imageFileName = file.getLastPathSegment();
    // TODO: check if image with same name already exists
    UploadTask uploadTask = mStorageRef.child(imageFileName).putFile(file, metadata);
    uploadTask.addOnFailureListener(new OnFailureListener() {

        @Override
        public void onFailure(@NonNull Exception e) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
            builder.setMessage("Upload failed. Please try again later.").setPositiveButton("OK", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Intent i = new Intent(StoryUpload.this, MapsActivityCurrentPlace.class);
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(i);
                }
            });
            builder.create().show();
        }
    }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {

        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
            uploadImageData(taskSnapshot);
        }
    });
}
Also used : StorageMetadata(com.google.firebase.storage.StorageMetadata) AlertDialog(android.support.v7.app.AlertDialog) DialogInterface(android.content.DialogInterface) Intent(android.content.Intent) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) UploadTask(com.google.firebase.storage.UploadTask) NonNull(android.support.annotation.NonNull) OnFailureListener(com.google.android.gms.tasks.OnFailureListener)

Example 3 with UploadTask

use of com.google.firebase.storage.UploadTask in project HikingApp by wickhama.

the class ImageTemp method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_image_temp);
    imageContainer = findViewById(R.id.imageButtonTest);
    uploadImage = (Button) findViewById(R.id.uploadImageTest);
    mAuth = FirebaseAuth.getInstance();
    currentUser = mAuth.getCurrentUser();
    /**
     * Anonymous Auth Again -- this will not be needed later as we should move this to a launch
     * activity.
     */
    mAuth.signInAnonymously().addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {

        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            if (task.isSuccessful()) {
                // Sign in success, update UI with the signed-in user's information
                System.out.println("***Anonymous User Authentication successful.");
                FirebaseUser user = mAuth.getCurrentUser();
            } else {
                // If sign in fails, display a message to the user.
                System.out.println("***Anonymous User Authentication failed.");
            }
        // ...
        }
    });
    /**
     * Getting images from the gallery.
     */
    uploadImage = (Button) findViewById(R.id.uploadImageTest);
    addImage = (ImageButton) findViewById(R.id.imageButtonTest);
    addImage.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
            galleryIntent.setType("image/*");
            startActivityForResult(galleryIntent, GALLERY_CODE);
        }
    });
    /**
     * UPLOADING images to Firebase Storage.
     */
    uploadImage.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (imageUri != null) {
                // added for UUID
                String path = "images/" + UUID.randomUUID() + ".jpg";
                storageRef = storage.getReference();
                imageRef = storageRef.child(path);
                uploadTask = storageRef.putFile(imageUri);
                imageRef.getName().equals(imageRef.getName());
                imageRef.getPath().equals(imageRef.getPath());
                Uri file = imageUri;
                // Sets path with UUID
                imageRef = storageRef.child(path);
                saveInternal(imageUri);
                uploadTask = imageRef.putFile(file);
                uploadTask.addOnFailureListener(new OnFailureListener() {

                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Toast.makeText(getApplicationContext(), "File Upload Failure.", Toast.LENGTH_LONG).show();
                        e.printStackTrace();
                    }
                }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {

                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        Toast.makeText(getApplicationContext(), "File Upload Success.", Toast.LENGTH_LONG).show();
                    // This will be needed when saving to the Trail object
                    /*
                            Uri downloadUrl = taskSnapshot.getDownloadUrl();
                            String url = downloadUrl.toString();
                            */
                    }
                });
            }
        }
    });
    /**
     * DOWNLOADING from Firebase Storage
     */
    // Hardcoded to get things working.
    String url = "https://firebasestorage.googleapis.com/v0/b/arctrails-b1a84.appspot.com/o/" + "images%2F20e1ee59-1fe1-4a05-82e8-9f40845ba6d5.jpg?alt=media&token=3b43df3d-1546-" + "4143-a8ae-2be667857cb5";
    StorageReference displayRef = storage.getReferenceFromUrl(url);
    ImageView displayImage = (ImageView) findViewById(R.id.photoHolder);
    Glide.with(ImageTemp.this).using(new FirebaseImageLoader()).load(displayRef).into(displayImage);
}
Also used : StorageReference(com.google.firebase.storage.StorageReference) AuthResult(com.google.firebase.auth.AuthResult) Intent(android.content.Intent) FirebaseUser(com.google.firebase.auth.FirebaseUser) ImageView(android.widget.ImageView) View(android.view.View) TextView(android.widget.TextView) Uri(android.net.Uri) FirebaseImageLoader(com.firebase.ui.storage.images.FirebaseImageLoader) IOException(java.io.IOException) UploadTask(com.google.firebase.storage.UploadTask) ImageView(android.widget.ImageView) OnSuccessListener(com.google.android.gms.tasks.OnSuccessListener) OnFailureListener(com.google.android.gms.tasks.OnFailureListener)

Example 4 with UploadTask

use of com.google.firebase.storage.UploadTask in project HikingApp by wickhama.

the class Database method uploadImage.

public void uploadImage(Uri imageUri, Trail trail, final Context context) {
    if (imageUri != null) {
        // added for UUID
        String path = "images/" + trail.getMetadata().getId() + ".jpg";
        storageRef = storage.getReference();
        imageRef = storageRef.child(path);
        uploadTask = storageRef.putFile(imageUri);
        imageRef.getName().equals(imageRef.getName());
        imageRef.getPath().equals(imageRef.getPath());
        Uri file = imageUri;
        // Sets path with UUID
        imageRef = storageRef.child(path);
        uploadTask = imageRef.putFile(file);
        uploadTask.addOnFailureListener(new OnFailureListener() {

            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(context, "File Upload Failure.", Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }
        }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {

            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                Toast.makeText(context, "File Upload Success.", Toast.LENGTH_LONG).show();
            // This will be needed when saving to the Trail object
            /*
                            Uri downloadUrl = taskSnapshot.getDownloadUrl();
                            String url = downloadUrl.toString();
                            */
            }
        });
    }
}
Also used : UploadTask(com.google.firebase.storage.UploadTask) NonNull(android.support.annotation.NonNull) Uri(android.net.Uri) OnFailureListener(com.google.android.gms.tasks.OnFailureListener)

Example 5 with UploadTask

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

the class ExpenseEdit method updateExpense.

private boolean updateExpense(final Expense expense) {
    Log.i(TAG, "update expense");
    if (!validateForm()) {
        Log.i(TAG, "submitted form is not valid");
        Toast.makeText(this, getString(R.string.invalid_form), Toast.LENGTH_SHORT).show();
        return false;
    }
    String newDescription = expenseDescriptionView.getText().toString();
    String newCurrency = expenseCurrencyView.getSelectedItem().toString();
    if (!newDescription.isEmpty() && (expense.getDescription() == null || !expense.getDescription().equals(newDescription))) {
        expense.setDescription(newDescription);
        databaseReference.child(expense_type).child(expense.getID()).child("description").setValue(expense.getDescription());
    }
    if (EXPENSE_TYPE.equals(Event.EventType.PENDING_EXPENSE_EDIT)) {
        Double newAmount = Double.valueOf(expenseAmountView.getText().toString());
        if (!newAmount.isNaN() && (expense.getAmount() == null || !expense.getAmount().equals(newAmount))) {
            expense.setAmount(newAmount);
            databaseReference.child(expense_type).child(expense.getID()).child("amount").setValue(expense.getAmount());
        }
    }
    if (!newCurrency.isEmpty() && (expense.getCurrency() == null || !expense.getCurrency().equals(newCurrency))) {
        expense.setCurrency(newCurrency);
        databaseReference.child(expense_type).child(expense.getID()).child("currency").setValue(expense.getCurrency());
    }
    if (IMAGE_CHANGED) {
        // for saving image
        StorageReference uExpenseImageImageFilenameRef = storageReference.child(expense_type).child(expense.getID()).child(expense.getID() + "_expensePhoto.jpg");
        // Get the data from an ImageView as bytes
        expenseImageView.setDrawingCacheEnabled(true);
        expenseImageView.buildDrawingCache();
        Bitmap bitmap = expenseImageView.getDrawingCache();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] data = baos.toByteArray();
        UploadTask uploadTask = uExpenseImageImageFilenameRef.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.
                expense.setExpensePhoto(taskSnapshot.getMetadata().getDownloadUrl().toString());
                databaseReference.child(expense_type).child(expense.getID()).child("expensePhoto").setValue(expense.getExpensePhoto());
            }
        });
    }
    if (BILL_CHANGED) {
        // for saving image
        StorageReference uExpenseBillImageFilenameRef = storageReference.child(expense_type).child(expense.getID()).child(expense.getID() + "billPhoto.jpg");
        // Get the data from an ImageView as bytes
        expenseBillView.setDrawingCacheEnabled(true);
        expenseBillView.buildDrawingCache();
        Bitmap bitmap = expenseBillView.getDrawingCache();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] data = baos.toByteArray();
        UploadTask uploadTask = uExpenseBillImageFilenameRef.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.
                expense.setBillPhoto(taskSnapshot.getMetadata().getDownloadUrl().toString());
                databaseReference.child(expense_type).child(expense.getID()).child("billPhoto").setValue(expense.getExpensePhoto());
            }
        });
    }
    // add event for EXPENSE_EDIT / PENDING_EXPENSE_EDIT
    databaseReference.child(expense_type).child(expense.getID()).addListenerForSingleValueEvent(new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            User currentUser = MainActivity.getCurrentUser();
            Event event = new Event(dataSnapshot.child("groupID").getValue(String.class), EXPENSE_TYPE, currentUser.getName() + " " + currentUser.getSurname(), dataSnapshot.child("description").getValue(String.class));
            event.setDate(new SimpleDateFormat("yyyy.MM.dd").format(new java.util.Date()));
            event.setTime(new SimpleDateFormat("HH:mm").format(new java.util.Date()));
            FirebaseUtils.getInstance().addEvent(event);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.w(TAG, databaseError.toException());
        }
    });
    return true;
}
Also used : User(com.polito.mad17.madmax.entities.User) StorageReference(com.google.firebase.storage.StorageReference) ByteArrayOutputStream(java.io.ByteArrayOutputStream) DataSnapshot(com.google.firebase.database.DataSnapshot) Bitmap(android.graphics.Bitmap) UploadTask(com.google.firebase.storage.UploadTask) DatabaseError(com.google.firebase.database.DatabaseError) NonNull(android.support.annotation.NonNull) Event(com.polito.mad17.madmax.entities.Event) ValueEventListener(com.google.firebase.database.ValueEventListener) SimpleDateFormat(java.text.SimpleDateFormat) OnFailureListener(com.google.android.gms.tasks.OnFailureListener)

Aggregations

UploadTask (com.google.firebase.storage.UploadTask)17 NonNull (android.support.annotation.NonNull)15 OnFailureListener (com.google.android.gms.tasks.OnFailureListener)14 ByteArrayOutputStream (java.io.ByteArrayOutputStream)13 StorageReference (com.google.firebase.storage.StorageReference)12 Bitmap (android.graphics.Bitmap)11 IOException (java.io.IOException)7 HashMap (java.util.HashMap)7 Intent (android.content.Intent)5 SimpleDateFormat (java.text.SimpleDateFormat)5 Map (java.util.Map)5 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 Uri (android.net.Uri)3 View (android.view.View)3 Event (com.polito.mad17.madmax.entities.Event)3 Compressor (id.zelory.compressor.Compressor)3