Search in sources :

Example 11 with OnFailureListener

use of com.google.android.gms.tasks.OnFailureListener 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 12 with OnFailureListener

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

the class LoginFragment method signIn.

private void signIn(String email, String password) {
    Log.i(TAG, "signIn");
    if (!validateForm()) {
        Log.i(TAG, "submitted form is not valid");
        Toast.makeText(getContext(), "Invalid form!", Toast.LENGTH_SHORT).show();
        return;
    }
    progressDialog.setMessage("Authentication, please wait...");
    progressDialog.show();
    // user authentication
    auth.signInWithEmailAndPassword(email, password).addOnFailureListener(new OnFailureListener() {

        @Override
        public void onFailure(@NonNull Exception e) {
            if (progressDialog.isShowing())
                progressDialog.dismiss();
            Log.i(TAG, "authentication failed, exception: " + e.toString());
            Toast.makeText(getContext(), "Authentication failed.\nPlease insert a valid email/password", Toast.LENGTH_LONG).show();
        }
    });
}
Also used : OnFailureListener(com.google.android.gms.tasks.OnFailureListener)

Example 13 with OnFailureListener

use of com.google.android.gms.tasks.OnFailureListener in project quickstart-android by firebase.

the class MainActivity method signInAnonymously.

private void signInAnonymously() {
    // Sign in anonymously. Authentication is required to read or write from Firebase Storage.
    showProgressDialog(getString(R.string.progress_auth));
    mAuth.signInAnonymously().addOnSuccessListener(this, new OnSuccessListener<AuthResult>() {

        @Override
        public void onSuccess(AuthResult authResult) {
            Log.d(TAG, "signInAnonymously:SUCCESS");
            hideProgressDialog();
            updateUI(authResult.getUser());
        }
    }).addOnFailureListener(this, new OnFailureListener() {

        @Override
        public void onFailure(@NonNull Exception exception) {
            Log.e(TAG, "signInAnonymously:FAILURE", exception);
            hideProgressDialog();
            updateUI(null);
        }
    });
}
Also used : AuthResult(com.google.firebase.auth.AuthResult) OnSuccessListener(com.google.android.gms.tasks.OnSuccessListener) OnFailureListener(com.google.android.gms.tasks.OnFailureListener)

Example 14 with OnFailureListener

use of com.google.android.gms.tasks.OnFailureListener in project quickstart-android by firebase.

the class MyUploadService method uploadFromUri.

// [START upload_from_uri]
private void uploadFromUri(final Uri fileUri) {
    Log.d(TAG, "uploadFromUri:src:" + fileUri.toString());
    // [START_EXCLUDE]
    taskStarted();
    showProgressNotification(getString(R.string.progress_uploading), 0, 0);
    // [END_EXCLUDE]
    // [START get_child_ref]
    // Get a reference to store file at photos/<FILENAME>.jpg
    final StorageReference photoRef = mStorageRef.child("photos").child(fileUri.getLastPathSegment());
    // [END get_child_ref]
    // Upload file to Firebase Storage
    Log.d(TAG, "uploadFromUri:dst:" + photoRef.getPath());
    photoRef.putFile(fileUri).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {

        @Override
        public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
            showProgressNotification(getString(R.string.progress_uploading), taskSnapshot.getBytesTransferred(), taskSnapshot.getTotalByteCount());
        }
    }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {

        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
            // Upload succeeded
            Log.d(TAG, "uploadFromUri:onSuccess");
            // Get the public download URL
            Uri downloadUri = taskSnapshot.getMetadata().getDownloadUrl();
            // [START_EXCLUDE]
            broadcastUploadFinished(downloadUri, fileUri);
            showUploadFinishedNotification(downloadUri, fileUri);
            taskCompleted();
        // [END_EXCLUDE]
        }
    }).addOnFailureListener(new OnFailureListener() {

        @Override
        public void onFailure(@NonNull Exception exception) {
            // Upload failed
            Log.w(TAG, "uploadFromUri:onFailure", exception);
            // [START_EXCLUDE]
            broadcastUploadFinished(null, fileUri);
            showUploadFinishedNotification(null, fileUri);
            taskCompleted();
        // [END_EXCLUDE]
        }
    });
}
Also used : UploadTask(com.google.firebase.storage.UploadTask) StorageReference(com.google.firebase.storage.StorageReference) OnSuccessListener(com.google.android.gms.tasks.OnSuccessListener) Uri(android.net.Uri) OnFailureListener(com.google.android.gms.tasks.OnFailureListener)

Example 15 with OnFailureListener

use of com.google.android.gms.tasks.OnFailureListener in project FirebaseUI-Android by firebase.

the class RegisterEmailFragment method registerUser.

private void registerUser(final String email, final String name, final String password) {
    mHelper.getFirebaseAuth().createUserWithEmailAndPassword(email, password).addOnFailureListener(new TaskFailureLogger(TAG, "Error creating user")).addOnSuccessListener(new OnSuccessListener<AuthResult>() {

        @Override
        public void onSuccess(AuthResult authResult) {
            // Set display name
            UserProfileChangeRequest changeNameRequest = new UserProfileChangeRequest.Builder().setDisplayName(name).setPhotoUri(mUser.getPhotoUri()).build();
            final FirebaseUser user = authResult.getUser();
            user.updateProfile(changeNameRequest).addOnFailureListener(new TaskFailureLogger(TAG, "Error setting display name")).addOnCompleteListener(new OnCompleteListener<Void>() {

                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    // This executes even if the name change fails, since
                    // the account creation succeeded and we want to save
                    // the credential to SmartLock (if enabled).
                    mHelper.saveCredentialsOrFinish(mSaveSmartLock, getActivity(), user, password, new IdpResponse(EmailAuthProvider.PROVIDER_ID, email));
                }
            });
        }
    }).addOnFailureListener(getActivity(), new OnFailureListener() {

        @Override
        public void onFailure(@NonNull Exception e) {
            mHelper.dismissDialog();
            if (e instanceof FirebaseAuthWeakPasswordException) {
                // Password too weak
                mPasswordInput.setError(getResources().getQuantityString(R.plurals.error_weak_password, R.integer.min_password_length));
            } else if (e instanceof FirebaseAuthInvalidCredentialsException) {
                // Email address is malformed
                mEmailInput.setError(getString(R.string.invalid_email_address));
            } else if (e instanceof FirebaseAuthUserCollisionException) {
                // Collision with existing user email, it should be very hard for
                // the user to even get to this error due to CheckEmailFragment.
                mEmailInput.setError(getString(R.string.error_user_collision));
            } else {
                // General error message, this branch should not be invoked but
                // covers future API changes
                mEmailInput.setError(getString(R.string.email_account_creation_error));
            }
        }
    });
}
Also used : TaskFailureLogger(com.firebase.ui.auth.ui.TaskFailureLogger) FirebaseAuthWeakPasswordException(com.google.firebase.auth.FirebaseAuthWeakPasswordException) UserProfileChangeRequest(com.google.firebase.auth.UserProfileChangeRequest) AuthResult(com.google.firebase.auth.AuthResult) FirebaseUser(com.google.firebase.auth.FirebaseUser) FirebaseAuthWeakPasswordException(com.google.firebase.auth.FirebaseAuthWeakPasswordException) FirebaseAuthInvalidCredentialsException(com.google.firebase.auth.FirebaseAuthInvalidCredentialsException) FirebaseAuthUserCollisionException(com.google.firebase.auth.FirebaseAuthUserCollisionException) FirebaseAuthInvalidCredentialsException(com.google.firebase.auth.FirebaseAuthInvalidCredentialsException) FirebaseAuthUserCollisionException(com.google.firebase.auth.FirebaseAuthUserCollisionException) OnSuccessListener(com.google.android.gms.tasks.OnSuccessListener) OnFailureListener(com.google.android.gms.tasks.OnFailureListener) IdpResponse(com.firebase.ui.auth.IdpResponse)

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