Search in sources :

Example 1 with User

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

the class PendingExpenseDetailActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    Log.d(TAG, "OnCreate");
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_pending_expense_detail);
    Intent intent = getIntent();
    expenseID = intent.getStringExtra("expenseID");
    // intent.getStringExtra("userID");
    userID = MainActivity.getCurrentUID();
    fab = (FloatingActionButton) findViewById(R.id.fab);
    updateFab(0);
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    toolbar.setBackgroundColor(0x0000FF00);
    // Get a support ActionBar corresponding to this toolbar
    ActionBar ab = getSupportActionBar();
    // Enable the Up button
    ab.setDisplayHomeAsUpEnabled(true);
    // insert tabs and current fragment in the main layout
    // mainView.addView(getLayoutInflater().inflate(R.layout.activity_expense_detail, null));
    TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
    tabLayout.addTab(tabLayout.newTab().setText(R.string.expense_detail));
    tabLayout.addTab(tabLayout.newTab().setText(R.string.comments));
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
    viewPager = (ViewPager) findViewById(R.id.expense_detail_view_pager);
    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            Log.d(TAG, String.valueOf(tab.getPosition()));
            updateFab(tab.getPosition());
            Log.d(TAG, "tab.getPosition() " + tab.getPosition());
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {
        }
    });
    ExpenseDetailPagerAdapter adapter = new ExpenseDetailPagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount(), expenseID, TAG);
    viewPager.setAdapter(adapter);
    viewPager.setCurrentItem(0);
    imageView = (ImageView) findViewById(R.id.img_photo);
    amountTextView = (TextView) findViewById(R.id.tv_amount);
    creatorNameTextView = (TextView) findViewById(R.id.tv_creator_name);
    groupTextView = (TextView) findViewById(R.id.tv_group_name);
    expenseNameTextView = (TextView) findViewById(R.id.tv_pending_name);
    moveExpenseButton = (Button) findViewById(R.id.btn_move_expense);
    // Retrieve data of this pending expense
    databaseReference.child("proposedExpenses").child(expenseID).addListenerForSingleValueEvent(new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            expenseName = dataSnapshot.child("description").getValue(String.class);
            String groupName = dataSnapshot.child("groupName").getValue(String.class);
            Double amount = dataSnapshot.child("amount").getValue(Double.class);
            expenseNameTextView.setText(expenseName);
            groupTextView.setText(groupName);
            amountTextView.setText(amount.toString());
            creatorID = dataSnapshot.child("creatorID").getValue(String.class);
            groupID = dataSnapshot.child("groupID").getValue(String.class);
            // .load(dataSnapshot.child("image").getValue(String.class))
            Glide.with(getApplicationContext()).load(dataSnapshot.child("expensePhoto").getValue(String.class)).placeholder(R.color.colorPrimary).centerCrop().diskCacheStrategy(DiskCacheStrategy.ALL).into(imageView);
            databaseReference.child("users").child(creatorID).addListenerForSingleValueEvent(new ValueEventListener() {

                @Override
                public void onDataChange(DataSnapshot creatorSnapshot) {
                    creatorNameTextView.setText(creatorSnapshot.child("name").getValue(String.class) + " " + creatorSnapshot.child("surname").getValue(String.class));
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                }
            });
            DecimalFormat df = new DecimalFormat("#.##");
            amountTextView.setText(df.format(amount) + " €");
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
    // Click on button to move from pending to real expense
    moveExpenseButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // Only the creator of pending expense can move it
            if (creatorID.equals(userID)) {
                databaseReference.child("proposedExpenses").child(expenseID).addListenerForSingleValueEvent(new ValueEventListener() {

                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        ArrayList<String> participants = new ArrayList<String>();
                        expenseName = dataSnapshot.child("description").getValue(String.class);
                        groupID = dataSnapshot.child("groupID").getValue(String.class);
                        Double amount = dataSnapshot.child("amount").getValue(Double.class);
                        String currency = dataSnapshot.child("currency").getValue(String.class);
                        String creatorID = dataSnapshot.child("creatorID").getValue(String.class);
                        String expensePhoto = dataSnapshot.child("expensePhoto").getValue(String.class);
                        for (DataSnapshot participantSnap : dataSnapshot.child("participants").getChildren()) participants.add(participantSnap.getKey());
                        Expense newExpense = new Expense();
                        newExpense.setDescription(expenseName);
                        newExpense.setAmount(amount);
                        newExpense.setCurrency(currency);
                        newExpense.setGroupID(groupID);
                        newExpense.setCreatorID(creatorID);
                        newExpense.setEquallyDivided(true);
                        newExpense.setDeleted(false);
                        newExpense.setExpensePhoto(expensePhoto);
                        Double amountPerMember = 1 / (double) participants.size();
                        for (String participant : participants) {
                            newExpense.getParticipants().put(participant, amountPerMember);
                            // Delete expense from his proposed expenses
                            databaseReference.child("users").child(participant).child("proposedExpenses").child(expenseID).setValue(false);
                        }
                        String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new java.util.Date());
                        newExpense.setTimestamp(timeStamp);
                        // Add expense to db
                        FirebaseUtils.getInstance().addExpenseFirebase(newExpense, null, null, getApplicationContext());
                        // Delete pending expense from proposed expenses list
                        databaseReference.child("proposedExpenses").child(expenseID).child("deleted").setValue(true);
                        // Delete pending expense from group
                        databaseReference.child("groups").child(groupID).child("proposedExpenses").child(expenseID).setValue(false);
                        // add event for PENDING_EXPENSE_APPROVED
                        User currentUser = MainActivity.getCurrentUser();
                        String userID = currentUser.getID();
                        Event event = new Event(groupID, Event.EventType.PENDING_EXPENSE_APPROVED, currentUser.getName() + " " + currentUser.getSurname(), newExpense.getDescription(), newExpense.getAmount());
                        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 myIntent = new Intent(PendingExpenseDetailActivity.this, GroupDetailActivity.class);
                        myIntent.putExtra("groupID", groupID);
                        myIntent.putExtra("userID", userID);
                        finish();
                        startActivity(myIntent);
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {
                    }
                });
            } else {
                Toast.makeText(PendingExpenseDetailActivity.this, getString(R.string.only_creator), Toast.LENGTH_SHORT).show();
                return;
            }
        }
    });
}
Also used : User(com.polito.mad17.madmax.entities.User) DecimalFormat(java.text.DecimalFormat) ArrayList(java.util.ArrayList) DataSnapshot(com.google.firebase.database.DataSnapshot) Expense(com.polito.mad17.madmax.entities.Expense) TabLayout(android.support.design.widget.TabLayout) ValueEventListener(com.google.firebase.database.ValueEventListener) ActionBar(android.support.v7.app.ActionBar) ExpenseDetailPagerAdapter(com.polito.mad17.madmax.activities.ExpenseDetailPagerAdapter) Intent(android.content.Intent) ImageView(android.widget.ImageView) View(android.view.View) TextView(android.widget.TextView) DatabaseError(com.google.firebase.database.DatabaseError) Event(com.polito.mad17.madmax.entities.Event) SimpleDateFormat(java.text.SimpleDateFormat)

Example 2 with User

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

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

the class ExpenseEdit method onCreate.

@Override
@TargetApi(23)
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.edit_expense);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    expenseImageView = (ImageView) this.findViewById(R.id.expense_image);
    expenseBillView = (ImageView) this.findViewById(R.id.expense_bill);
    expenseDescriptionView = (EditText) this.findViewById(R.id.expense_description);
    expenseAmountView = (EditText) this.findViewById(R.id.expense_amount);
    expenseCurrencyView = (Spinner) this.findViewById(R.id.expense_currency);
    saveButton = (Button) this.findViewById(R.id.btn_save);
    // creating spinner for currencies
    final ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.currencies, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    expenseCurrencyView.setAdapter(adapter);
    Intent intent = getIntent();
    String expenseID = intent.getStringExtra("expenseID");
    if (intent.getStringExtra("EXPENSE_TYPE").equals("EXPENSE_EDIT")) {
        EXPENSE_TYPE = Event.EventType.EXPENSE_EDIT;
        expense_type = "expenses";
    } else {
        EXPENSE_TYPE = Event.EventType.PENDING_EXPENSE_EDIT;
        expense_type = "proposedExpenses";
    }
    databaseReference.child(expense_type).child(expenseID).addListenerForSingleValueEvent(new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            expense = new Expense();
            expense.setID(dataSnapshot.getKey());
            expense.setDescription(dataSnapshot.child("description").getValue(String.class));
            expense.setCurrency(dataSnapshot.child("currency").getValue(String.class));
            expense.setExpensePhoto(dataSnapshot.child("expensePhoto").getValue(String.class));
            expense.setBillPhoto(dataSnapshot.child("billPhoto").getValue(String.class));
            final String groupID = dataSnapshot.child("groupID").getValue(String.class);
            expenseDescriptionView.setText(expense.getDescription());
            if (EXPENSE_TYPE.equals(Event.EventType.PENDING_EXPENSE_EDIT)) {
                expense.setAmount(dataSnapshot.child("amount").getValue(Double.class));
                expenseAmountView.setText(String.valueOf(expense.getAmount()));
            }
            // set the defaultCurrency value for the spinner based on the user preferences
            int spinnerPosition = adapter.getPosition(expense.getCurrency());
            expenseCurrencyView.setSelection(spinnerPosition);
            // progressDialog = new ProgressDialog(ProfileEdit.this);
            // loading expense photo (if present)
            String expenseImage = expense.getExpensePhoto();
            if (expenseImage != null && !expenseImage.equals("")) {
                // Loading image
                Glide.with(getApplicationContext()).load(expenseImage).centerCrop().diskCacheStrategy(DiskCacheStrategy.ALL).into(expenseImageView);
            } else {
                // Loading image
                expenseImageView.setImageResource(R.drawable.add_photo);
            /* Glide.with(getApplicationContext()).load(R.drawable.add_photo)
                            .centerCrop()
                            //.bitmapTransform(new CropCircleTransformation(this))
                            .diskCacheStrategy(DiskCacheStrategy.ALL)
                            .into(expenseImageView);*/
            }
            expenseImageView.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    Log.i(TAG, "expense image clicked");
                    if (MainActivity.shouldAskPermission()) {
                        String[] perms = { "android.permission.READ_EXTERNAL_STORAGE" };
                        int permsRequestCode = 200;
                        requestPermissions(perms, permsRequestCode);
                    }
                    // allow to the user the choose image
                    Intent intent = new Intent();
                    // Show only images, no videos or anything else
                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    // Always show the chooser (if there are multiple options available)
                    startActivityForResult(Intent.createChooser(intent, "Select picture"), PICK_IMAGE_REQUEST);
                // now see onActivityResult
                }
            });
            // loading expense bill (if present)
            String expenseBill = expense.getBillPhoto();
            if (expenseBill != null && !expenseBill.equals("")) {
                // Loading image
                Glide.with(getApplicationContext()).load(expenseBill).centerCrop().diskCacheStrategy(DiskCacheStrategy.ALL).into(expenseBillView);
            } else {
                // Loading image
                expenseImageView.setImageResource(R.drawable.add_photo);
            /*Glide.with(getApplicationContext()).load(R.drawable.add_photo)
                            .centerCrop()
                            //.bitmapTransform(new CropCircleTransformation(this))
                            .diskCacheStrategy(DiskCacheStrategy.ALL)
                            .into(expenseBillView);*/
            }
            expenseBillView.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    Log.i(TAG, "expense bill clicked");
                    if (MainActivity.shouldAskPermission()) {
                        String[] perms = { "android.permission.READ_EXTERNAL_STORAGE" };
                        int permsRequestCode = 200;
                        requestPermissions(perms, permsRequestCode);
                    }
                    // allow to the user the choose image
                    Intent intent = new Intent();
                    // Show only images, no videos or anything else
                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    // Always show the chooser (if there are multiple options available)
                    startActivityForResult(Intent.createChooser(intent, "Select picture"), PICK_BILL_REQUEST);
                // now see onActivityResult
                }
            });
            saveButton.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    Log.i(TAG, "save clicked");
                    if (updateExpense(expense)) {
                        Toast.makeText(ExpenseEdit.this, getString(R.string.saved), Toast.LENGTH_SHORT).show();
                        Intent intent;
                        if (EXPENSE_TYPE.equals(Event.EventType.EXPENSE_EDIT)) {
                            intent = new Intent(getApplicationContext(), ExpenseDetailActivity.class);
                            intent.putExtra("groupID", expense.getGroupID());
                            intent.putExtra("expenseID", expense.getID());
                            intent.putExtra("userID", MainActivity.getCurrentUser().getID());
                        } else {
                            intent = new Intent(getApplicationContext(), MainActivity.class);
                            intent.putExtra("currentFragment", 2);
                        }
                        startActivity(intent);
                        finish();
                    }
                }
            });
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.w(TAG, databaseError.getMessage());
        }
    });
}
Also used : Intent(android.content.Intent) MainActivity(com.polito.mad17.madmax.activities.MainActivity) DataSnapshot(com.google.firebase.database.DataSnapshot) ImageView(android.widget.ImageView) View(android.view.View) DatabaseError(com.google.firebase.database.DatabaseError) Expense(com.polito.mad17.madmax.entities.Expense) ValueEventListener(com.google.firebase.database.ValueEventListener) TargetApi(android.annotation.TargetApi)

Example 4 with User

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

the class NewExpenseActivity method addUnequalExpense.

void addUnequalExpense(final Expense newExpense, String groupID, HashMap<String, Double> participants) {
    // getParticipants.value is the FRACTION that the user will pay
    for (Map.Entry<String, Double> entry : participants.entrySet()) {
        Double fraction = entry.getValue() / newExpense.getAmount();
        newExpense.getParticipants().put(entry.getKey(), fraction);
    }
    String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new java.util.Date());
    newExpense.setTimestamp(timeStamp);
    if (!IMAGE_CHANGED)
        expensePhoto = null;
    if (!BILL_CHANGED)
        billPhoto = null;
    // Aggiungo una pending expense
    if (callingActivity.equals("ChooseGroupActivity")) {
        newExpense.setGroupName(groupName);
        if (groupImage != null)
            newExpense.setGroupImage(groupImage);
        FirebaseUtils.getInstance().addPendingExpenseFirebase(newExpense, expensePhoto, getApplicationContext());
        // add event for PENDING_EXPENSE_ADD
        User currentUser = MainActivity.getCurrentUser();
        Event event = new Event(groupID, Event.EventType.PENDING_EXPENSE_ADD, currentUser.getName() + " " + currentUser.getSurname(), newExpense.getDescription(), newExpense.getAmount());
        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 myIntent = new Intent(NewExpenseActivity.this, MainActivity.class);
        myIntent.putExtra("UID", MainActivity.getCurrentUser().getID());
        myIntent.putExtra("currentFragment", 2);
        startActivity(myIntent);
    } else // Aggiungo una spesa normale
    {
        FirebaseUtils.getInstance().addExpenseFirebase(newExpense, expensePhoto, billPhoto, getApplicationContext());
        // add event for EXPENSE_ADD
        User currentUser = MainActivity.getCurrentUser();
        Event event = new Event(newExpense.getGroupID(), Event.EventType.EXPENSE_ADD, currentUser.getName() + " " + currentUser.getSurname(), newExpense.getDescription(), newExpense.getAmount());
        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);
    }
}
Also used : User(com.polito.mad17.madmax.entities.User) Event(com.polito.mad17.madmax.entities.Event) MotionEvent(android.view.MotionEvent) Intent(android.content.Intent) HashMap(java.util.HashMap) Map(java.util.Map) SimpleDateFormat(java.text.SimpleDateFormat)

Example 5 with User

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

the class NewExpenseActivity method addEqualExpense.

void addEqualExpense(final Expense newExpense, final String groupID) {
    DatabaseReference groupRef = databaseReference.child("groups");
    groupRef.child(groupID).child("members").addListenerForSingleValueEvent(new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot membersSnapshot) {
            int participantsCount = 0;
            // Attenzione! Non contare i membri eliminati tra i partecipanti alla spesa
            for (DataSnapshot memberSnap : membersSnapshot.getChildren()) {
                if (!memberSnap.child("deleted").getValue(Boolean.class)) {
                    participantsCount++;
                }
            }
            Double amountPerMember = 1 / (double) participantsCount;
            for (DataSnapshot member : membersSnapshot.getChildren()) {
                // Aggiungo alla spesa solo i membri non eliminati dal gruppo
                if (!member.child("deleted").getValue(Boolean.class)) {
                    newExpense.getParticipants().put(member.getKey(), amountPerMember);
                }
            }
            String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new java.util.Date());
            newExpense.setTimestamp(timeStamp);
            if (!IMAGE_CHANGED)
                expensePhoto = null;
            if (!BILL_CHANGED)
                billPhoto = null;
            // Aggiungo una pending expense
            if (callingActivity.equals("ChooseGroupActivity")) {
                newExpense.setGroupName(groupName);
                if (groupImage != null)
                    newExpense.setGroupImage(groupImage);
                FirebaseUtils.getInstance().addPendingExpenseFirebase(newExpense, expensePhoto, getApplicationContext());
                // add event for PENDING_EXPENSE_ADD
                User currentUser = MainActivity.getCurrentUser();
                Event event = new Event(groupID, Event.EventType.PENDING_EXPENSE_ADD, currentUser.getName() + " " + currentUser.getSurname(), newExpense.getDescription(), newExpense.getAmount());
                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 myIntent = new Intent(NewExpenseActivity.this, MainActivity.class);
                myIntent.putExtra("UID", MainActivity.getCurrentUID());
                myIntent.putExtra("currentFragment", 2);
                startActivity(myIntent);
            } else // Aggiungo una spesa normale
            {
                FirebaseUtils.getInstance().addExpenseFirebase(newExpense, expensePhoto, billPhoto, getApplicationContext());
                // add event for EXPENSE_ADD
                User currentUser = MainActivity.getCurrentUser();
                Event event = new Event(newExpense.getGroupID(), Event.EventType.EXPENSE_ADD, currentUser.getName() + " " + currentUser.getSurname(), newExpense.getDescription(), newExpense.getAmount());
                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 error) {
            // Failed to read value
            Log.w(TAG, "Failed to read value.", error.toException());
        }
    });
}
Also used : User(com.polito.mad17.madmax.entities.User) DatabaseReference(com.google.firebase.database.DatabaseReference) Intent(android.content.Intent) MainActivity(com.polito.mad17.madmax.activities.MainActivity) DataSnapshot(com.google.firebase.database.DataSnapshot) DatabaseError(com.google.firebase.database.DatabaseError) Event(com.polito.mad17.madmax.entities.Event) MotionEvent(android.view.MotionEvent) ValueEventListener(com.google.firebase.database.ValueEventListener) 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