Search in sources :

Example 21 with ValueEventListener

use of com.google.firebase.database.ValueEventListener 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)

Example 22 with ValueEventListener

use of com.google.firebase.database.ValueEventListener in project MadMax by deviz92.

the class FriendsFragment method onCreateView.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final String activityName = getActivity().getClass().getSimpleName();
    Log.d(TAG, "Sono nella activity: " + activityName);
    final View view = inflater.inflate(R.layout.skeleton_list, container, false);
    databaseReference = FirebaseDatabase.getInstance().getReference();
    friends.clear();
    setInterface((OnItemClickInterface) getActivity(), (OnItemLongClickInterface) getActivity());
    RecyclerView.ItemDecoration divider = new InsetDivider.Builder(getContext()).orientation(InsetDivider.VERTICAL_LIST).dividerHeight(getResources().getDimensionPixelSize(R.dimen.divider_height)).color(ContextCompat.getColor(getContext(), R.color.colorDivider)).insets(getResources().getDimensionPixelSize(R.dimen.divider_inset), 0).overlay(true).build();
    recyclerView = (RecyclerView) view.findViewById(R.id.rv_skeleton);
    layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.addItemDecoration(divider);
    friendsViewAdapter = new FriendsViewAdapter(this.getContext(), this, this, friends, groupDetail);
    recyclerView.setAdapter(friendsViewAdapter);
    // Se sono in MainActivity visualizzo lista degli amici
    if (activityName.equals("MainActivity")) {
        query = databaseReference.child("users").child(MainActivity.getCurrentUID()).child("friends");
    } else // Se sono dentro un gruppo, visualizzo lista membri del gruppo
    if (activityName.equals("GroupDetailActivity")) {
        Bundle b = this.getArguments();
        if (b != null) {
            groupID = b.getString("groupID");
            query = databaseReference.child("groups").child(groupID).child("members");
        }
    }
    Log.d(TAG, "query: " + query);
    groupMembersListener = query.addValueEventListener(new ValueEventListener() {

        @Override
        public void onDataChange(final DataSnapshot externalDataSnapshot) {
            // svuoto la map, così se viene eliminato uno user dal db, non viene tenuto nella map che si ricarica da zero
            friends.clear();
            for (final DataSnapshot friendSnapshot : externalDataSnapshot.getChildren()) {
                // getFriend(friendSnapshot.getKey());
                if (activityName.equals("MainActivity")) {
                    Log.d(TAG, "key: " + friendSnapshot.getKey());
                    Log.d(TAG, "value: " + friendSnapshot.getValue());
                    if (!listenedFriends)
                        listenedFriends = true;
                    // Log.d(TAG,  friendSnapshot.child("deleted").getValue() + " ");
                    deleted = friendSnapshot.child("deleted").getValue(Boolean.class);
                    if (deleted == null) {
                        deleted = true;
                    }
                    if (deleted)
                        Log.d(TAG, friendSnapshot.getKey() + " is cancelled");
                } else if (activityName.equals("GroupDetailActivity")) {
                    deleted = friendSnapshot.child("deleted").getValue(Boolean.class);
                    if (deleted == null) {
                        deleted = true;
                    }
                    // Se sono negli amici "generali" e non nei membri di un gruppo, non c'è il campo deleted, quindi sarà null
                    if (!listenedGroups.contains(groupID))
                        listenedGroups.add(groupID);
                }
                if (!deleted) {
                    final String id = friendSnapshot.getKey();
                    databaseReference.child("users").child(id).addValueEventListener(new ValueEventListener() {

                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            String name = dataSnapshot.child("name").getValue(String.class);
                            String surname = dataSnapshot.child("surname").getValue(String.class);
                            String profileImage = dataSnapshot.child("image").getValue(String.class);
                            if (activityName.equals("MainActivity")) {
                                User u = new User();
                                u.setID(friendSnapshot.getKey());
                                u.setName(name);
                                u.setSurname(surname);
                                u.setProfileImage(profileImage);
                                if (!deleted)
                                    friends.put(id, u);
                                else
                                    friends.remove(id);
                                friendsViewAdapter.update(friends);
                                friendsViewAdapter.notifyDataSetChanged();
                            } else if (activityName.equals("GroupDetailActivity")) {
                                getUserAndGroupBalance(id, name, surname, profileImage, groupID);
                            }
                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {
                        }
                    });
                }
            }
            friendsViewAdapter.update(friends);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.w(TAG, databaseError.getMessage());
        }
    });
    Log.d(TAG, "dopo setAdapter");
    return view;
}
Also used : User(com.polito.mad17.madmax.entities.User) Bundle(android.os.Bundle) LinearLayoutManager(android.support.v7.widget.LinearLayoutManager) DataSnapshot(com.google.firebase.database.DataSnapshot) View(android.view.View) RecyclerView(android.support.v7.widget.RecyclerView) DatabaseError(com.google.firebase.database.DatabaseError) RecyclerView(android.support.v7.widget.RecyclerView) ValueEventListener(com.google.firebase.database.ValueEventListener)

Example 23 with ValueEventListener

use of com.google.firebase.database.ValueEventListener in project MadMax by deviz92.

the class FirebaseUtils method removeExpenseFirebase.

public void removeExpenseFirebase(final String expenseID, final Context context) {
    databaseReference.child("expenses").child(expenseID).addValueEventListener(new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            String groupID = dataSnapshot.child("groupID").getValue(String.class);
            // aggiunto da riky per mandare la notifica a tutti tranne a chi ha eliminato la spesa
            databaseReference.child("expenses").child(expenseID).child("deletedBy").setValue(MainActivity.getCurrentUID());
            // Elimino spesa dal gruppo
            databaseReference.child("groups").child(groupID).child("expenses").child(expenseID).setValue(false);
            // Per ogni participant elimino la spesa dal suo elenco spese
            for (DataSnapshot participantSnapshot : dataSnapshot.child("participants").getChildren()) {
                String participantID = participantSnapshot.getKey();
                databaseReference.child("users").child(participantID).child("expenses").child(expenseID).setValue(false);
            }
            // Elimino commenti sulla spesa
            databaseReference.child("comments").child(groupID).removeValue();
            // Elimino spesa
            databaseReference.child("expenses").child(expenseID).child("deleted").setValue(true);
            // Toast.makeText(context,context.getString(R.string.expense_removed),Toast.LENGTH_SHORT).show();
            // add event for EXPENSE_REMOVE
            databaseReference.child("expenses").child(expenseID).addListenerForSingleValueEvent(new ValueEventListener() {

                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    User currentUser = MainActivity.getCurrentUser();
                    Event event = new Event(dataSnapshot.child("groupID").getValue(String.class), Event.EventType.EXPENSE_REMOVE, 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());
                }
            });
        /*Intent intent = new Intent(context, GroupDetailActivity.class);
                intent.putExtra("groupID", groupID);
                intent.putExtra("userID", MainActivity.getCurrentUID());
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);*/
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
}
Also used : User(com.polito.mad17.madmax.entities.User) DatabaseError(com.google.firebase.database.DatabaseError) Event(com.polito.mad17.madmax.entities.Event) ValueEventListener(com.google.firebase.database.ValueEventListener) DataSnapshot(com.google.firebase.database.DataSnapshot) SimpleDateFormat(java.text.SimpleDateFormat)

Example 24 with ValueEventListener

use of com.google.firebase.database.ValueEventListener in project MadMax by deviz92.

the class FirebaseUtils method removePendingExpenseFirebase.

public void removePendingExpenseFirebase(final String expenseID, final Context context) {
    databaseReference.child("proposedExpenses").child(expenseID).addValueEventListener(new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            String groupID = dataSnapshot.child("groupID").getValue(String.class);
            // Elimino spesa pending dal gruppo
            databaseReference.child("groups").child(groupID).child("proposedExpenses").child(expenseID).setValue(false);
            // Per ogni participant elimino la spesa pending dal suo elenco spese pending
            for (DataSnapshot participantSnapshot : dataSnapshot.child("participants").getChildren()) {
                String participantID = participantSnapshot.getKey();
                databaseReference.child("users").child(participantID).child("proposedExpenses").child(expenseID).setValue(false);
            }
            // todo Elimino commenti sulla spesa pending
            // databaseReference.child("comments").child(groupID).removeValue();
            // Elimino spesa pending
            databaseReference.child("proposedExpenses").child(expenseID).child("deleted").setValue(true);
            // Toast.makeText(context, context.getString(R.string.expense_removed), Toast.LENGTH_SHORT).show();
            // add event for PENDING_EXPENSE_REMOVE
            databaseReference.child("proposedExpenses").child(expenseID).addListenerForSingleValueEvent(new ValueEventListener() {

                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    User currentUser = MainActivity.getCurrentUser();
                    Event event = new Event(dataSnapshot.child("groupID").getValue(String.class), Event.EventType.PENDING_EXPENSE_REMOVE, 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());
                }
            });
        /*Intent intent = new Intent(context, MainActivity.class);
                intent.putExtra("currentFragment", 2);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);*/
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
}
Also used : User(com.polito.mad17.madmax.entities.User) DatabaseError(com.google.firebase.database.DatabaseError) Event(com.polito.mad17.madmax.entities.Event) ValueEventListener(com.google.firebase.database.ValueEventListener) DataSnapshot(com.google.firebase.database.DataSnapshot) SimpleDateFormat(java.text.SimpleDateFormat)

Example 25 with ValueEventListener

use of com.google.firebase.database.ValueEventListener in project quickstart-android by firebase.

the class NewPostActivity method submitPost.

private void submitPost() {
    final String title = mTitleField.getText().toString();
    final String body = mBodyField.getText().toString();
    // Title is required
    if (TextUtils.isEmpty(title)) {
        mTitleField.setError(REQUIRED);
        return;
    }
    // Body is required
    if (TextUtils.isEmpty(body)) {
        mBodyField.setError(REQUIRED);
        return;
    }
    // Disable button so there are no multi-posts
    setEditingEnabled(false);
    Toast.makeText(this, "Posting...", Toast.LENGTH_SHORT).show();
    // [START single_value_read]
    final String userId = getUid();
    mDatabase.child("users").child(userId).addListenerForSingleValueEvent(new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            // Get user value
            User user = dataSnapshot.getValue(User.class);
            // [START_EXCLUDE]
            if (user == null) {
                // User is null, error out
                Log.e(TAG, "User " + userId + " is unexpectedly null");
                Toast.makeText(NewPostActivity.this, "Error: could not fetch user.", Toast.LENGTH_SHORT).show();
            } else {
                // Write new post
                writeNewPost(userId, user.username, title, body);
            }
            // Finish this Activity, back to the stream
            setEditingEnabled(true);
            finish();
        // [END_EXCLUDE]
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.w(TAG, "getUser:onCancelled", databaseError.toException());
            // [START_EXCLUDE]
            setEditingEnabled(true);
        // [END_EXCLUDE]
        }
    });
// [END single_value_read]
}
Also used : User(com.google.firebase.quickstart.database.models.User) DatabaseError(com.google.firebase.database.DatabaseError) ValueEventListener(com.google.firebase.database.ValueEventListener) DataSnapshot(com.google.firebase.database.DataSnapshot)

Aggregations

DataSnapshot (com.google.firebase.database.DataSnapshot)44 DatabaseError (com.google.firebase.database.DatabaseError)44 ValueEventListener (com.google.firebase.database.ValueEventListener)44 View (android.view.View)19 LinearLayoutManager (android.support.v7.widget.LinearLayoutManager)12 RecyclerView (android.support.v7.widget.RecyclerView)12 User (com.polito.mad17.madmax.entities.User)12 Intent (android.content.Intent)11 Bundle (android.os.Bundle)10 DatabaseReference (com.google.firebase.database.DatabaseReference)9 TextView (android.widget.TextView)7 ImageView (android.widget.ImageView)6 Event (com.polito.mad17.madmax.entities.Event)5 SimpleDateFormat (java.text.SimpleDateFormat)5 HashMap (java.util.HashMap)4 TabLayout (android.support.design.widget.TabLayout)3 Query (com.google.firebase.database.Query)3 ArrayList (java.util.ArrayList)3 TargetApi (android.annotation.TargetApi)2 SharedPreferences (android.content.SharedPreferences)2