Search in sources :

Example 6 with UploadTask

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

the class GroupEdit method updateGroup.

private boolean updateGroup(final Group group) {
    Log.i(TAG, "update group");
    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 newName = groupNameView.getText().toString();
    String newDescription = groupDescriptionView.getText().toString();
    if (!newName.isEmpty() && (group.getName() == null || !group.getName().equals(newName))) {
        group.setName(newName);
        databaseReference.child("groups").child(group.getID()).child("name").setValue(group.getName());
    }
    if (!newDescription.isEmpty() && (group.getDescription() == null || !group.getDescription().equals(newDescription))) {
        group.setDescription(newDescription);
        databaseReference.child("groups").child(group.getID()).child("description").setValue(group.getDescription());
    }
    if (IMAGE_CHANGED) {
        // for saving image
        StorageReference uGroupImageImageFilenameRef = storageReference.child("groups").child(group.getID()).child(group.getID() + "_groupImage.jpg");
        // Get the data from an ImageView as bytes
        groupImageView.setDrawingCacheEnabled(true);
        groupImageView.buildDrawingCache();
        Bitmap bitmap = groupImageView.getDrawingCache();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] data = baos.toByteArray();
        UploadTask uploadTask = uGroupImageImageFilenameRef.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.
                group.setImage(taskSnapshot.getMetadata().getDownloadUrl().toString());
                databaseReference.child("groups").child(group.getID()).child("image").setValue(group.getImage());
            }
        });
    }
    // add event for GROUP_EDIT
    User currentUser = MainActivity.getCurrentUser();
    Event event = new Event(group.getID(), Event.EventType.GROUP_EDIT, currentUser.getName() + " " + currentUser.getSurname(), group.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);
    return true;
}
Also used : User(com.polito.mad17.madmax.entities.User) 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) Event(com.polito.mad17.madmax.entities.Event) SimpleDateFormat(java.text.SimpleDateFormat) OnFailureListener(com.google.android.gms.tasks.OnFailureListener)

Example 7 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, "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 8 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, 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)

Example 9 with UploadTask

use of com.google.firebase.storage.UploadTask in project PhotoBlog-Android-Blog-App by akshayejh.

the class NewPostActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_new_post);
    storageReference = FirebaseStorage.getInstance().getReference();
    firebaseFirestore = FirebaseFirestore.getInstance();
    firebaseAuth = FirebaseAuth.getInstance();
    current_user_id = firebaseAuth.getCurrentUser().getUid();
    newPostToolbar = findViewById(R.id.new_post_toolbar);
    setSupportActionBar(newPostToolbar);
    getSupportActionBar().setTitle("Add New Post");
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    newPostImage = findViewById(R.id.new_post_image);
    newPostDesc = findViewById(R.id.new_post_desc);
    newPostBtn = findViewById(R.id.post_btn);
    newPostProgress = findViewById(R.id.new_post_progress);
    newPostImage.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            CropImage.activity().setGuidelines(CropImageView.Guidelines.ON).setMinCropResultSize(512, 512).setAspectRatio(1, 1).start(NewPostActivity.this);
        }
    });
    newPostBtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            final String desc = newPostDesc.getText().toString();
            if (!TextUtils.isEmpty(desc) && postImageUri != null) {
                newPostProgress.setVisibility(View.VISIBLE);
                final String randomName = UUID.randomUUID().toString();
                // PHOTO UPLOAD
                File newImageFile = new File(postImageUri.getPath());
                try {
                    compressedImageFile = new Compressor(NewPostActivity.this).setMaxHeight(720).setMaxWidth(720).setQuality(50).compressToBitmap(newImageFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                compressedImageFile.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                byte[] imageData = baos.toByteArray();
                // PHOTO UPLOAD
                UploadTask filePath = storageReference.child("post_images").child(randomName + ".jpg").putBytes(imageData);
                filePath.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {

                    @Override
                    public void onComplete(@NonNull final Task<UploadTask.TaskSnapshot> task) {
                        final String downloadUri = task.getResult().getDownloadUrl().toString();
                        if (task.isSuccessful()) {
                            File newThumbFile = new File(postImageUri.getPath());
                            try {
                                compressedImageFile = new Compressor(NewPostActivity.this).setMaxHeight(100).setMaxWidth(100).setQuality(1).compressToBitmap(newThumbFile);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
                            compressedImageFile.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                            byte[] thumbData = baos.toByteArray();
                            UploadTask uploadTask = storageReference.child("post_images/thumbs").child(randomName + ".jpg").putBytes(thumbData);
                            uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {

                                @Override
                                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                                    String downloadthumbUri = taskSnapshot.getDownloadUrl().toString();
                                    Map<String, Object> postMap = new HashMap<>();
                                    postMap.put("image_url", downloadUri);
                                    postMap.put("image_thumb", downloadthumbUri);
                                    postMap.put("desc", desc);
                                    postMap.put("user_id", current_user_id);
                                    postMap.put("timestamp", FieldValue.serverTimestamp());
                                    firebaseFirestore.collection("Posts").add(postMap).addOnCompleteListener(new OnCompleteListener<DocumentReference>() {

                                        @Override
                                        public void onComplete(@NonNull Task<DocumentReference> task) {
                                            if (task.isSuccessful()) {
                                                Toast.makeText(NewPostActivity.this, "Post was added", Toast.LENGTH_LONG).show();
                                                Intent mainIntent = new Intent(NewPostActivity.this, MainActivity.class);
                                                startActivity(mainIntent);
                                                finish();
                                            } else {
                                            }
                                            newPostProgress.setVisibility(View.INVISIBLE);
                                        }
                                    });
                                }
                            }).addOnFailureListener(new OnFailureListener() {

                                @Override
                                public void onFailure(@NonNull Exception e) {
                                // Error handling
                                }
                            });
                        } else {
                            newPostProgress.setVisibility(View.INVISIBLE);
                        }
                    }
                });
            }
        }
    });
}
Also used : Task(com.google.android.gms.tasks.Task) UploadTask(com.google.firebase.storage.UploadTask) HashMap(java.util.HashMap) UploadTask(com.google.firebase.storage.UploadTask) NonNull(android.support.annotation.NonNull) OnSuccessListener(com.google.android.gms.tasks.OnSuccessListener) DocumentReference(com.google.firebase.firestore.DocumentReference) Compressor(id.zelory.compressor.Compressor) Intent(android.content.Intent) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ImageView(android.widget.ImageView) CropImageView(com.theartofdev.edmodo.cropper.CropImageView) View(android.view.View) IOException(java.io.IOException) OnCompleteListener(com.google.android.gms.tasks.OnCompleteListener) File(java.io.File) OnFailureListener(com.google.android.gms.tasks.OnFailureListener)

Example 10 with UploadTask

use of com.google.firebase.storage.UploadTask in project PhotoBlog-Android-Blog-App by akshayejh.

the class SetupActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_setup);
    Toolbar setupToolbar = findViewById(R.id.setupToolbar);
    setSupportActionBar(setupToolbar);
    getSupportActionBar().setTitle("Account Setup");
    firebaseAuth = FirebaseAuth.getInstance();
    user_id = firebaseAuth.getCurrentUser().getUid();
    firebaseFirestore = FirebaseFirestore.getInstance();
    storageReference = FirebaseStorage.getInstance().getReference();
    setupImage = findViewById(R.id.setup_image);
    setupName = findViewById(R.id.setup_name);
    setupBtn = findViewById(R.id.setup_btn);
    setupProgress = findViewById(R.id.setup_progress);
    setupProgress.setVisibility(View.VISIBLE);
    setupBtn.setEnabled(false);
    firebaseFirestore.collection("Users").document(user_id).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {

        @Override
        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
            if (task.isSuccessful()) {
                if (task.getResult().exists()) {
                    String name = task.getResult().getString("name");
                    String image = task.getResult().getString("image");
                    mainImageURI = Uri.parse(image);
                    setupName.setText(name);
                    RequestOptions placeholderRequest = new RequestOptions();
                    placeholderRequest.placeholder(R.drawable.default_image);
                    Glide.with(SetupActivity.this).setDefaultRequestOptions(placeholderRequest).load(image).into(setupImage);
                }
            } else {
                String error = task.getException().getMessage();
                Toast.makeText(SetupActivity.this, "(FIRESTORE Retrieve Error) : " + error, Toast.LENGTH_LONG).show();
            }
            setupProgress.setVisibility(View.INVISIBLE);
            setupBtn.setEnabled(true);
        }
    });
    setupBtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            final String user_name = setupName.getText().toString();
            if (!TextUtils.isEmpty(user_name) && mainImageURI != null) {
                setupProgress.setVisibility(View.VISIBLE);
                if (isChanged) {
                    user_id = firebaseAuth.getCurrentUser().getUid();
                    File newImageFile = new File(mainImageURI.getPath());
                    try {
                        compressedImageFile = new Compressor(SetupActivity.this).setMaxHeight(125).setMaxWidth(125).setQuality(50).compressToBitmap(newImageFile);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    compressedImageFile.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                    byte[] thumbData = baos.toByteArray();
                    UploadTask image_path = storageReference.child("profile_images").child(user_id + ".jpg").putBytes(thumbData);
                    image_path.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {

                        @Override
                        public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
                            if (task.isSuccessful()) {
                                storeFirestore(task, user_name);
                            } else {
                                String error = task.getException().getMessage();
                                Toast.makeText(SetupActivity.this, "(IMAGE Error) : " + error, Toast.LENGTH_LONG).show();
                                setupProgress.setVisibility(View.INVISIBLE);
                            }
                        }
                    });
                } else {
                    storeFirestore(null, user_name);
                }
            }
        }
    });
    setupImage.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (ContextCompat.checkSelfPermission(SetupActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(SetupActivity.this, "Permission Denied", Toast.LENGTH_LONG).show();
                    ActivityCompat.requestPermissions(SetupActivity.this, new String[] { Manifest.permission.READ_EXTERNAL_STORAGE }, 1);
                } else {
                    BringImagePicker();
                }
            } else {
                BringImagePicker();
            }
        }
    });
}
Also used : Task(com.google.android.gms.tasks.Task) UploadTask(com.google.firebase.storage.UploadTask) RequestOptions(com.bumptech.glide.request.RequestOptions) Compressor(id.zelory.compressor.Compressor) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) CircleImageView(de.hdodenhof.circleimageview.CircleImageView) CropImageView(com.theartofdev.edmodo.cropper.CropImageView) View(android.view.View) DocumentSnapshot(com.google.firebase.firestore.DocumentSnapshot) UploadTask(com.google.firebase.storage.UploadTask) OnCompleteListener(com.google.android.gms.tasks.OnCompleteListener) NonNull(android.support.annotation.NonNull) File(java.io.File) Toolbar(android.support.v7.widget.Toolbar)

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