Search in sources :

Example 36 with User

use of com.polito.mad17.madmax.entities.User in project MadMax by deviz92.

the class GroupsFragment method getGroupAndBalance.

/*    void getGroupAndBalance (final String userID, final String groupID)
    {

        //final HashMap <String, Double> totalBalance = new HashMap<>();
        final HashMap <String, Expense> groupExpenses = new HashMap<>();
        //totalBalance.put(userID,0d);
        //totBalance = 0d;
        final HashMap <String, Double> totBalances = new HashMap<>();
        totBalances.clear();

        groupListener = databaseReference.child("groups").child(groupID).addValueEventListener(new ValueEventListener() {

            @Override
            public void onDataChange(final DataSnapshot groupDataSnapshot) {

                //totalBalance.put(userID,0d);
                totBalances.clear();
                if (!listenedGroups.contains(groupID))
                    listenedGroups.add(groupID);

                final Boolean deleted = groupDataSnapshot.child("deleted").getValue(Boolean.class);

                if (deleted != null)
                {
                    for (DataSnapshot groupExpenseSnapshot: groupDataSnapshot.child("expenses").getChildren())
                    {
                        //Contribuiscono al bilancio solo le spese non eliminate dal gruppo
                        if (groupExpenseSnapshot.getValue(Boolean.class) == true)
                        {
                            //Adesso sono sicuro che la spesa non è stata eliminata
                            //Ascolto la singola spesa del gruppo
                            String expenseID = groupExpenseSnapshot.getKey();
                            databaseReference.child("expenses").child(expenseID).addListenerForSingleValueEvent(new ValueEventListener() {
                                @Override
                                public void onDataChange(DataSnapshot dataSnapshot) {

                                    Boolean involved = false; //dice se user contribuisce o no a quella spesa

                                    for (DataSnapshot participantSnapshot: dataSnapshot.child("participants").getChildren())
                                    {
                                        //todo poi gestire caso in cui utente viene tolto dai participant alla spesa
                                        if (participantSnapshot.getKey().equals(userID))
                                            involved = true;
                                    }

                                    //se user ha partecipato alla spesa
                                    if (involved)
                                    {
                                        //alreadyPaid = soldi già messi dallo user per quella spesa
                                        //dueImport = quota che user deve mettere per quella spesa
                                        //balance = credito/debito dello user per quella spesa
                                        for (DataSnapshot d : dataSnapshot.child("participants").getChildren())
                                        {
                                            Log.d (TAG, "PartCampo " + d.getKey() + ": " + d.getValue() );
                                        }
                                        Double alreadyPaid = dataSnapshot.child("participants").child(userID).child("alreadyPaid").getValue(Double.class);

                                        Log.d (TAG, "Fraction: " + Double.parseDouble(String.valueOf(dataSnapshot.child("participants").child(userID).child("fraction").getValue())));

                                        Double dueImport = Double.parseDouble(String.valueOf(dataSnapshot.child("participants").child(userID).child("fraction").getValue())) * dataSnapshot.child("amount").getValue(Double.class);
                                        if (alreadyPaid != null && dueImport != null)
                                        {
                                            Double balance = alreadyPaid - dueImport;
                                            String currency = dataSnapshot.child("currency").getValue(String.class);
                                            //se user per quella spesa ha già pagato più soldi della sua quota, il balance è positivo

                                            //current balance for that currency
                                            Double temp = totBalances.get(currency);
                                            //update balance for that currency
                                            if (temp != null)
                                            {
                                                totBalances.put(currency, temp + balance);
                                             //   Log.d (TAG, "Actual debt for " + groupName + ": " + totBalances.get(currency) + " " + currency);
                                            }
                                            else
                                            {
                                                totBalances.put(currency, balance);
                                             //   Log.d (TAG, "Actual debt for " + groupName + ": " + totBalances.get(currency) + " " + currency);

                                            }
                                            //Double currentBalance = totalBalance.get(userID);
                                            //totalBalance.put(userID, currentBalance+balance);
                                            //totBalance += balance;

                                            Expense expense = new Expense();
                                            expense.setID(dataSnapshot.getKey());
                                            expense.setCurrency(dataSnapshot.child("currency").getValue(String.class));
                                            expense.setAmount(dataSnapshot.child("amount").getValue(Double.class));

                                            groupExpenses.put(dataSnapshot.getKey(), expense);

                                            Log.d(TAG, "added expense " + dataSnapshot.getKey());
                                        }
                                        else
                                        {
                                            Log.d (TAG, "Qui sarebbe crashato");
                                        }


                                    }
                                }

                                @Override
                                public void onCancelled(DatabaseError databaseError) {

                                }
                            });
                        }
                    }

                    Group group = new Group();
                    group.setName(groupDataSnapshot.child("name").getValue(String.class));
                    group.setImage(groupDataSnapshot.child("image").getValue(String.class));
                    group.setDeleted(deleted);
                    group.setBalance(0d);
                    group.setCurrencyBalances(totBalances);
                    group.setExpenses(groupExpenses);

                    if (!deleted &&
                            groupDataSnapshot.child("members").hasChild(MainActivity.getCurrentUID()) &&
                            !groupDataSnapshot.child("members").child(MainActivity.getCurrentUID()).child("deleted").getValue(Boolean.class)) {
                        groups.put(groupID, group);
                    }
                    else
                    {
                        groups.remove(groupID);
                    }

//                    Group nullGroup = new Group();
//                    nullGroup.setID(groupID + 1);
//                    groups.put(nullGroup.getID(), nullGroup);

                    groupsViewAdapter.update(groups);
                    groupsViewAdapter.notifyDataSetChanged();
                    //totBalance = 0d;
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
            }
        });


        return ;
    }*/
// versione di ale
// /versione più complessa dell getGroup. Quest'ultima non verrà più usata.
// oltre al nome gruppo, prende anche il bilancio dello user col gruppo
void getGroupAndBalance(final String userID, final String groupID) {
    // final HashMap <String, Double> totalBalance = new HashMap<>();
    final HashMap<String, Expense> groupExpenses = new HashMap<>();
    // totalBalance.put(userID,0d);
    // totBalance = 0d;
    final HashMap<String, Double> totBalances = new HashMap<>();
    totBalances.clear();
    groupListener = databaseReference.child("groups").child(groupID).addValueEventListener(new ValueEventListener() {

        @Override
        public void onDataChange(final DataSnapshot groupDataSnapshot) {
            // totalBalance.put(userID,0d);
            totBalances.clear();
            if (!listenedGroups.contains(groupID))
                listenedGroups.add(groupID);
            final String groupName = groupDataSnapshot.child("name").getValue(String.class);
            final Boolean deleted = groupDataSnapshot.child("deleted").getValue(Boolean.class);
            if (deleted != null) {
                for (DataSnapshot groupExpenseSnapshot : groupDataSnapshot.child("expenses").getChildren()) {
                    // Contribuiscono al bilancio solo le spese non eliminate dal gruppo
                    if (groupExpenseSnapshot.getValue(Boolean.class) == true) {
                        // Adesso sono sicuro che la spesa non è stata eliminata
                        // Ascolto la singola spesa del gruppo
                        String expenseID = groupExpenseSnapshot.getKey();
                        databaseReference.child("expenses").child(expenseID).addListenerForSingleValueEvent(new ValueEventListener() {

                            @Override
                            public void onDataChange(DataSnapshot dataSnapshot) {
                                // dice se user contribuisce o no a quella spesa
                                Boolean involved = false;
                                for (DataSnapshot participantSnapshot : dataSnapshot.child("participants").getChildren()) {
                                    // todo poi gestire caso in cui utente viene tolto dai participant alla spesa
                                    if (participantSnapshot.getKey().equals(userID))
                                        involved = true;
                                }
                                // se user ha partecipato alla spesa
                                if (involved) {
                                    // balance = credito/debito dello user per quella spesa
                                    for (DataSnapshot d : dataSnapshot.child("participants").getChildren()) {
                                        Log.d(TAG, "PartCampo " + d.getKey() + ": " + d.getValue());
                                    }
                                    Double alreadyPaid = dataSnapshot.child("participants").child(userID).child("alreadyPaid").getValue(Double.class);
                                    // If has been made to avoid crash
                                    if (dataSnapshot.child("participants").child(userID).hasChild("fraction") && dataSnapshot.hasChild("amount")) {
                                        Log.d(TAG, "Fraction: " + Double.parseDouble(String.valueOf(dataSnapshot.child("participants").child(userID).child("fraction").getValue())));
                                        Double dueImport = Double.parseDouble(String.valueOf(dataSnapshot.child("participants").child(userID).child("fraction").getValue())) * dataSnapshot.child("amount").getValue(Double.class);
                                        if (alreadyPaid != null && dueImport != null) {
                                            Double balance = alreadyPaid - dueImport;
                                            String currency = dataSnapshot.child("currency").getValue(String.class);
                                            // se user per quella spesa ha già pagato più soldi della sua quota, il balance è positivo
                                            // current balance for that currency
                                            Double temp = totBalances.get(currency);
                                            // update balance for that currency
                                            if (temp != null) {
                                                totBalances.put(currency, temp + balance);
                                                Log.d(TAG, "Actual debt for " + groupName + ": " + totBalances.get(currency) + " " + currency);
                                            } else {
                                                totBalances.put(currency, balance);
                                                Log.d(TAG, "Actual debt for " + groupName + ": " + totBalances.get(currency) + " " + currency);
                                            }
                                            // Double currentBalance = totalBalance.get(userID);
                                            // totalBalance.put(userID, currentBalance+balance);
                                            // totBalance += balance;
                                            Expense expense = new Expense();
                                            expense.setID(dataSnapshot.getKey());
                                            expense.setCurrency(dataSnapshot.child("currency").getValue(String.class));
                                            expense.setAmount(dataSnapshot.child("amount").getValue(Double.class));
                                            groupExpenses.put(dataSnapshot.getKey(), expense);
                                            Log.d(TAG, "added expense " + dataSnapshot.getKey());
                                        } else {
                                            Log.d(TAG, "Qui sarebbe crashato");
                                        }
                                    }
                                }
                                Group g = new Group();
                                g.setName(groupName);
                                // g.setBalance(totalBalance.get(userID));
                                g.setCurrencyBalances(totBalances);
                                g.setExpenses(groupExpenses);
                                g.setDeleted(deleted);
                                g.setImage(groupDataSnapshot.child("image").getValue(String.class));
                                // se il gruppo non è deleted e io faccio ancora parte del gruppo
                                if (!deleted && groupDataSnapshot.child("members").hasChild(MainActivity.getCurrentUID()) && !groupDataSnapshot.child("members").child(MainActivity.getCurrentUID()).child("deleted").getValue(Boolean.class)) {
                                    groups.put(groupID, g);
                                } else {
                                    groups.remove(groupID);
                                }
                                groupsViewAdapter.update(groups);
                                groupsViewAdapter.notifyDataSetChanged();
                            }

                            @Override
                            public void onCancelled(DatabaseError databaseError) {
                            }
                        });
                    }
                }
                // Per gestire il caso di quando ho appena abbandonato o eliminato il gruppo
                // if (dataSnapshot.child("members").hasChild(userID))
                // {
                Group g = new Group();
                g.setName(groupName);
                g.setImage(groupDataSnapshot.child("image").getValue(String.class));
                g.setBalance(0d);
                g.setDeleted(deleted);
                if (!deleted && groupDataSnapshot.child("members").hasChild(MainActivity.getCurrentUID()) && !groupDataSnapshot.child("members").child(MainActivity.getCurrentUID()).child("deleted").getValue(Boolean.class)) {
                    groups.put(groupID, g);
                } else {
                    groups.remove(groupID);
                }
                // Group nullGroup = new Group();
                // nullGroup.setID(groupID + 1);
                // groups.put(nullGroup.getID(), nullGroup);
                groupsViewAdapter.update(groups);
                groupsViewAdapter.notifyDataSetChanged();
            // totBalance = 0d;
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
    return;
}
Also used : ViewGroup(android.view.ViewGroup) Group(com.polito.mad17.madmax.entities.Group) DatabaseError(com.google.firebase.database.DatabaseError) Expense(com.polito.mad17.madmax.entities.Expense) HashMap(java.util.HashMap) ValueEventListener(com.google.firebase.database.ValueEventListener) DataSnapshot(com.google.firebase.database.DataSnapshot)

Example 37 with User

use of com.polito.mad17.madmax.entities.User 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)

Aggregations

User (com.polito.mad17.madmax.entities.User)27 Intent (android.content.Intent)17 DataSnapshot (com.google.firebase.database.DataSnapshot)16 DatabaseError (com.google.firebase.database.DatabaseError)16 ValueEventListener (com.google.firebase.database.ValueEventListener)16 Event (com.polito.mad17.madmax.entities.Event)15 SimpleDateFormat (java.text.SimpleDateFormat)14 View (android.view.View)8 HashMap (java.util.HashMap)8 Map (java.util.Map)8 ImageView (android.widget.ImageView)6 CropCircleTransformation (com.polito.mad17.madmax.entities.CropCircleTransformation)6 Bitmap (android.graphics.Bitmap)4 NonNull (android.support.annotation.NonNull)4 LinearLayoutManager (android.support.v7.widget.LinearLayoutManager)4 RecyclerView (android.support.v7.widget.RecyclerView)4 StorageReference (com.google.firebase.storage.StorageReference)4 UploadTask (com.google.firebase.storage.UploadTask)4 Group (com.polito.mad17.madmax.entities.Group)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4