Search in sources :

Example 11 with UploadTask

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

the class MultiSquawk 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(MultiSquawk.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 12 with UploadTask

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

the class SignUpFragment method sendVerificationEmail.

private void sendVerificationEmail() {
    Log.i(TAG, "sendVerificationEmail");
    final FirebaseUser user = auth.getCurrentUser();
    if (user == null) {
        Log.e(TAG, "Error while retriving current user from db");
        Toast.makeText(getContext(), getString(R.string.error_user_db), Toast.LENGTH_LONG).show();
        return;
    }
    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this.getContext());
    String defaultCurrency = sharedPref.getString(SettingsFragment.DEFAULT_CURRENCY, "");
    String UID = user.getUid();
    final User u = new User(UID, usernameView.getText().toString(), nameView.getText().toString(), surnameView.getText().toString(), emailView.getText().toString(), passwordView.getText().toString(), "", defaultCurrency);
    progressDialog.setMessage("Sending email verification, please wait...");
    progressDialog.show();
    // inserimento dell'utente a db (tranne la foto)
    HashMap<String, String> newUserEntry = new HashMap<>();
    newUserEntry.put("email", u.getEmail());
    newUserEntry.put("password", u.getPassword());
    newUserEntry.put("name", u.getName());
    newUserEntry.put("surname", u.getSurname());
    newUserEntry.put("username", u.getUsername());
    databaseReference.child("users").child(u.getID()).setValue(newUserEntry);
    Log.i(TAG, "new user sent into db");
    // for saving image
    if (imageSetted) {
        StorageReference uProfileImageFilenameRef = storageReference.child("users").child(UID).child(UID + "_profileImage.jpg");
        // Get the data from an ImageView as bytes
        profileImageView.setDrawingCacheEnabled(true);
        profileImageView.buildDrawingCache();
        Bitmap bitmap = profileImageView.getDrawingCache();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] data = baos.toByteArray();
        UploadTask uploadTask = uProfileImageFilenameRef.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.
                // inserimento della foto a db
                u.setProfileImage(taskSnapshot.getMetadata().getDownloadUrl().toString());
                databaseReference.child("users").child(u.getID()).child("image").setValue(u.getProfileImage());
                user.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {

                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        progressDialog.dismiss();
                        if (task.isSuccessful()) {
                            Log.i(TAG, "verification email successfully sent");
                            Toast.makeText(getContext(), R.string.emailVerification_text, Toast.LENGTH_LONG).show();
                        } else {
                            databaseReference.child("users").child(u.getID()).removeValue();
                            user.delete();
                            Log.d(TAG, "user deleted from db");
                            Log.e(TAG, "verification email not sent, exception: " + task.getException());
                        }
                        onClickSignUpInterface.itemClicked(SignUpFragment.class.getSimpleName(), "1");
                    }
                });
            }
        });
    } else {
        user.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {

            @Override
            public void onComplete(@NonNull Task<Void> task) {
                progressDialog.dismiss();
                if (task.isSuccessful()) {
                    Log.i(TAG, "verification email successful sent");
                    Toast.makeText(getContext(), R.string.emailVerification_text, Toast.LENGTH_LONG).show();
                } else {
                    databaseReference.child("users").child(u.getID()).removeValue();
                    user.delete();
                    Log.d(TAG, "user deleted from db");
                    Log.e(TAG, "verification email not sent, exception: " + task.getException());
                }
                onClickSignUpInterface.itemClicked(SignUpFragment.class.getSimpleName(), "1");
            }
        });
    }
}
Also used : Task(com.google.android.gms.tasks.Task) UploadTask(com.google.firebase.storage.UploadTask) User(com.polito.mad17.madmax.entities.User) FirebaseUser(com.google.firebase.auth.FirebaseUser) StorageReference(com.google.firebase.storage.StorageReference) SharedPreferences(android.content.SharedPreferences) HashMap(java.util.HashMap) FirebaseUser(com.google.firebase.auth.FirebaseUser) ByteArrayOutputStream(java.io.ByteArrayOutputStream) FirebaseAuthWeakPasswordException(com.google.firebase.auth.FirebaseAuthWeakPasswordException) FirebaseAuthUserCollisionException(com.google.firebase.auth.FirebaseAuthUserCollisionException) IOException(java.io.IOException) Bitmap(android.graphics.Bitmap) UploadTask(com.google.firebase.storage.UploadTask) OnCompleteListener(com.google.android.gms.tasks.OnCompleteListener) NonNull(android.support.annotation.NonNull) OnFailureListener(com.google.android.gms.tasks.OnFailureListener)

Example 13 with UploadTask

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

the class ProfileEdit method updateAccount.

private boolean updateAccount() {
    Log.i(TAG, "createAccount");
    if (!validateForm()) {
        Log.i(TAG, "submitted form is not valid");
        Toast.makeText(this, getString(R.string.invalid_form), Toast.LENGTH_SHORT).show();
        return false;
    }
    final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    if (user == null) {
        Log.e(TAG, "Error while retriving current user from db");
        Toast.makeText(this, getString(R.string.error_user_db), Toast.LENGTH_LONG).show();
        return false;
    }
    final String currentUserID = currentUser.getID();
    String newName = nameView.getText().toString();
    String newSurname = surnameView.getText().toString();
    String newUsername = usernameView.getText().toString();
    // String newEmail = emailView.getText().toString();
    String newPassword = passwordView.getText().toString();
    if (!newName.isEmpty() && (currentUser.getName() == null || !currentUser.getName().equals(newName))) {
        currentUser.setName(newName);
        databaseReference.child("users").child(currentUserID).child("name").setValue(currentUser.getName());
    }
    if (!newSurname.isEmpty() && (currentUser.getSurname() == null || !currentUser.getSurname().equals(newSurname))) {
        currentUser.setSurname(newSurname);
        databaseReference.child("users").child(currentUserID).child("surname").setValue(currentUser.getSurname());
    }
    if (!newUsername.isEmpty() && (currentUser.getUsername() == null || !currentUser.getUsername().equals(newUsername))) {
        currentUser.setUsername(newUsername);
        databaseReference.child("users").child(currentUserID).child("username").setValue(currentUser.getUsername());
    }
    if (IMAGE_CHANGED) {
        // for saving image
        StorageReference uProfileImageFilenameRef = storageReference.child("users").child(currentUserID).child(currentUserID + "_profileImage.jpg");
        // Get the data from an ImageView as bytes
        profileImageView.setDrawingCacheEnabled(true);
        profileImageView.buildDrawingCache();
        Bitmap bitmap = profileImageView.getDrawingCache();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] data = baos.toByteArray();
        UploadTask uploadTask = uProfileImageFilenameRef.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.
                currentUser.setProfileImage(taskSnapshot.getMetadata().getDownloadUrl().toString());
                databaseReference.child("users").child(currentUserID).child("image").setValue(currentUser.getProfileImage());
            }
        });
    }
    if (!newPassword.isEmpty() && !currentUser.getPassword().equals(User.encryptPassword(newPassword))) {
        try {
            user.updatePassword(newPassword);
        } catch (Exception e) {
            Log.e(TAG, e.getClass().toString() + ", message: " + e.getMessage());
            Toast.makeText(this, getString(R.string.error_password), Toast.LENGTH_LONG).show();
            return false;
        }
        currentUser.setPassword(newPassword);
        databaseReference.child("users").child(currentUserID).child("password").setValue(currentUser.getPassword());
    }
    return true;
}
Also used : StorageReference(com.google.firebase.storage.StorageReference) FirebaseUser(com.google.firebase.auth.FirebaseUser) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Bitmap(android.graphics.Bitmap) UploadTask(com.google.firebase.storage.UploadTask) NonNull(android.support.annotation.NonNull) OnFailureListener(com.google.android.gms.tasks.OnFailureListener)

Example 14 with UploadTask

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

the class NewGroupActivity method onOptionsItemSelected.

// When i click SAVE
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int itemThatWasClickedId = item.getItemId();
    if (itemThatWasClickedId == R.id.action_save) {
        // display message if text field is empty
        if (TextUtils.isEmpty(nameGroup.getText().toString())) {
            nameGroup.setError(getString(R.string.required));
            return false;
        }
        Log.d(TAG, "Second step: invite members to group");
        // String deepLink = getString(R.string.invitation_deep_link) + "?groupToBeAddedID=" + groupID+ "?inviterToGroupUID=" + MainActivity.getCurrentUID();
        newgroup_id = databaseReference.child("groups").push().getKey();
        String name = nameGroup.getText().toString();
        String description = descriptionGroup.getText().toString();
        // id is useless
        final Group newGroup = new Group("0", name, "noImage", description, 1);
        // for saving image
        StorageReference uProfileImageFilenameRef = storageReference.child("groups").child(newgroup_id).child(newgroup_id + "_profileImage.jpg");
        // Get the data from an ImageView as bytes
        imageGroup.setDrawingCacheEnabled(true);
        imageGroup.buildDrawingCache();
        Bitmap bitmap = imageGroup.getDrawingCache();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] imageData = baos.toByteArray();
        UploadTask uploadTask = uProfileImageFilenameRef.putBytes(imageData);
        uploadTask.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {

            @Override
            public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
                if (task.isSuccessful()) {
                    newGroup.setImage(task.getResult().getDownloadUrl().toString());
                    Log.d(TAG, "group img url: " + newGroup.getImage());
                    databaseReference.child("groups").child(newgroup_id).setValue(newGroup);
                    String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new java.util.Date());
                    databaseReference.child("groups").child(newgroup_id).child("timestamp").setValue(timeStamp);
                    databaseReference.child("groups").child(newgroup_id).child("numberMembers").setValue(1);
                    FirebaseUtils.getInstance().joinGroupFirebase(MainActivity.getCurrentUID(), newgroup_id);
                    Log.d(TAG, "group " + newgroup_id + " created");
                    // add event for GROUP_ADD
                    User currentUser = MainActivity.getCurrentUser();
                    Event event = new Event(newgroup_id, Event.EventType.GROUP_ADD, currentUser.getName() + " " + currentUser.getSurname(), newGroup.getName());
                    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);
                }
            }
        });
        Intent intent = new Intent(getApplicationContext(), NewMemberActivity.class);
        intent.putExtra("groupID", newgroup_id);
        intent.putExtra("groupName", name);
        startActivity(intent);
        finish();
        return true;
    }
    return super.onOptionsItemSelected(item);
}
Also used : Group(com.polito.mad17.madmax.entities.Group) User(com.polito.mad17.madmax.entities.User) StorageReference(com.google.firebase.storage.StorageReference) Intent(android.content.Intent) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Bitmap(android.graphics.Bitmap) UploadTask(com.google.firebase.storage.UploadTask) Event(com.polito.mad17.madmax.entities.Event) MotionEvent(android.view.MotionEvent) SimpleDateFormat(java.text.SimpleDateFormat)

Example 15 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, Context context) {
    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);
    // timestamp già settato prima
    // 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;
    StorageReference uExpensePhotoFilenameRef = storageReference.child("expenses").child(eID).child(eID + "_expensePhoto.jpg");
    // Get the data from an ImageView as bytes
    if (expense.getExpensePhoto() == null) {
        if (expensePhoto != null) {
            expensePhoto.setDrawingCacheEnabled(true);
            expensePhoto.buildDrawingCache();
            bitmap = expensePhoto.getDrawingCache();
        } else {
            bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.expense_default);
        }
        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
        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)

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