Search in sources :

Example 21 with OnFailureListener

use of com.google.android.gms.tasks.OnFailureListener 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, "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, "Error while retriving current user from 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, "Can't update 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 22 with OnFailureListener

use of com.google.android.gms.tasks.OnFailureListener 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(), "Error while retriving current user from 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();
    // 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.
                u.setProfileImage(taskSnapshot.getMetadata().getDownloadUrl().toString());
                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");
                            Log.i(TAG, "insert new user into db");
                            HashMap<String, String> newUserEntry = new HashMap<>();
                            newUserEntry.put("email", u.getEmail());
                            newUserEntry.put("password", u.getPassword());
                            //                                    newUserEntry.put("friends", u.getUserFriends().toString());
                            //                                    newUserEntry.put("groups", u.getUserGroups().toString());
                            newUserEntry.put("image", u.getProfileImage());
                            newUserEntry.put("name", u.getName());
                            newUserEntry.put("surname", u.getSurname());
                            newUserEntry.put("username", u.getUsername());
                            databaseReference.child("users").child(u.getID()).setValue(newUserEntry);
                            Toast.makeText(getContext(), R.string.emailVerification_text, Toast.LENGTH_LONG).show();
                        } else {
                            // todo delete the account and restart the activity
                            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");
                    Log.i(TAG, "insert new user into db");
                    HashMap<String, String> newUserEntry = new HashMap<>();
                    newUserEntry.put("email", u.getEmail());
                    newUserEntry.put("password", u.getPassword());
                    //                        newUserEntry.put("friends", u.getUserFriends().toString());
                    //                        newUserEntry.put("groups", u.getUserGroups().toString());
                    newUserEntry.put("image", u.getProfileImage());
                    newUserEntry.put("name", u.getName());
                    newUserEntry.put("surname", u.getSurname());
                    newUserEntry.put("username", u.getUsername());
                    databaseReference.child("users").child(u.getID()).setValue(newUserEntry);
                    Toast.makeText(getContext(), R.string.emailVerification_text, Toast.LENGTH_LONG).show();
                } else {
                    // todo delete the account and restart the activity
                    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) HashMap(java.util.HashMap) Bitmap(android.graphics.Bitmap) UploadTask(com.google.firebase.storage.UploadTask) NonNull(android.support.annotation.NonNull) StorageReference(com.google.firebase.storage.StorageReference) SharedPreferences(android.content.SharedPreferences) 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) OnCompleteListener(com.google.android.gms.tasks.OnCompleteListener) OnFailureListener(com.google.android.gms.tasks.OnFailureListener)

Example 23 with OnFailureListener

use of com.google.android.gms.tasks.OnFailureListener in project MadMax by deviz92.

the class FirebaseUtils method addPendingExpenseFirebase.

public void addPendingExpenseFirebase(Expense expense, ImageView expensePhoto, ImageView billPhoto) {
    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");
    // Get the data from an ImageView as bytes
    expensePhoto.setDrawingCacheEnabled(true);
    expensePhoto.buildDrawingCache();
    Bitmap bitmap = expensePhoto.getDrawingCache();
    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)

Aggregations

OnFailureListener (com.google.android.gms.tasks.OnFailureListener)23 OnSuccessListener (com.google.android.gms.tasks.OnSuccessListener)14 StorageReference (com.google.firebase.storage.StorageReference)8 UploadTask (com.google.firebase.storage.UploadTask)6 NonNull (android.support.annotation.NonNull)5 TaskFailureLogger (com.firebase.ui.auth.ui.TaskFailureLogger)5 FirebaseUser (com.google.firebase.auth.FirebaseUser)5 File (java.io.File)5 Bitmap (android.graphics.Bitmap)4 AuthResult (com.google.firebase.auth.AuthResult)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 Uri (android.net.Uri)3 FirebaseAuthUserCollisionException (com.google.firebase.auth.FirebaseAuthUserCollisionException)3 FileDownloadTask (com.google.firebase.storage.FileDownloadTask)3 StorageMetadata (com.google.firebase.storage.StorageMetadata)3 HashMap (java.util.HashMap)3 IdpResponse (com.firebase.ui.auth.IdpResponse)2 AuthCredential (com.google.firebase.auth.AuthCredential)2 FirebaseAuthWeakPasswordException (com.google.firebase.auth.FirebaseAuthWeakPasswordException)2 IOException (java.io.IOException)2