Search in sources :

Example 11 with Expense

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

the class ExpenseDetailActivity method onOptionsItemSelected.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    Intent intent;
    Log.d(TAG, "Clicked item: " + item.getItemId());
    switch(item.getItemId()) {
        case R.id.one:
            Log.d(TAG, "clicked Modify expense");
            intent = new Intent(this, ExpenseEdit.class);
            intent.putExtra("expenseID", expenseID);
            intent.putExtra("EXPENSE_TYPE", "EXPENSE_EDIT");
            startActivity(intent);
            finish();
            return true;
        case R.id.two:
            Log.d(TAG, "clicked Remove expense");
            FirebaseUtils.getInstance().removeExpenseFirebase(expenseID, getApplicationContext());
            finish();
            return true;
        case android.R.id.home:
            Log.d(TAG, "Clicked up button on ExpenseDetailActivity");
            intent = new Intent(this, GroupDetailActivity.class);
            intent.putExtra("groupID", groupID);
            intent.putExtra("userID", userID);
            setResult(RESULT_OK, intent);
            finish();
            return (true);
    }
    return (super.onOptionsItemSelected(item));
}
Also used : GroupDetailActivity(com.polito.mad17.madmax.activities.groups.GroupDetailActivity) Intent(android.content.Intent)

Example 12 with Expense

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

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

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

the class ExpensesViewAdapter method onBindViewHolder.

@Override
public void onBindViewHolder(final ItemExpensesViewHolder expensesViewHolder, int position) {
    if (position == (expenses.size() - 1)) {
        Log.d(TAG, "item.getKey().equals(\"nullGroup\")");
        expensesViewHolder.imageView.setVisibility(View.INVISIBLE);
        expensesViewHolder.nameTextView.setText("");
        expensesViewHolder.balanceTextTextView.setText("");
        expensesViewHolder.balanceTextView.setText("");
    } else {
        Expense expense = getItem(position).getValue();
        Log.d(TAG, "item ID " + expense.getID() + " image " + expense.getExpensePhoto());
        expensesViewHolder.imageView.setVisibility(View.VISIBLE);
        if (expense.getExpensePhoto() != null && !expense.getExpensePhoto().equals("noImage")) {
            Log.d(TAG, "Image not null");
            Glide.with(layoutInflater.getContext()).load(expense.getExpensePhoto()).centerCrop().bitmapTransform(new CropCircleTransformation(layoutInflater.getContext())).diskCacheStrategy(DiskCacheStrategy.ALL).into(expensesViewHolder.imageView);
        } else {
            Glide.with(layoutInflater.getContext()).load(R.drawable.expense_default).centerCrop().bitmapTransform(new CropCircleTransformation(layoutInflater.getContext())).diskCacheStrategy(DiskCacheStrategy.ALL).into(expensesViewHolder.imageView);
        }
        expensesViewHolder.nameTextView.setText(expense.getDescription());
        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
        String defaultCurrency = sharedPref.getString(SettingsFragment.DEFAULT_CURRENCY, "");
        Double expenseBalance = expense.getBalance();
        String balance = Math.abs(expenseBalance) + " " + expense.getCurrency();
        if (expenseBalance > 0) {
            expensesViewHolder.balanceTextTextView.setText(R.string.credit_of);
            expensesViewHolder.balanceTextTextView.setTextColor(ContextCompat.getColor(context, R.color.colorPrimaryDark));
            expensesViewHolder.balanceTextView.setText(balance);
            expensesViewHolder.balanceTextView.setTextColor(ContextCompat.getColor(context, R.color.colorPrimaryDark));
        } else {
            if (expenseBalance < 0) {
                expensesViewHolder.balanceTextTextView.setText(R.string.debt_of);
                expensesViewHolder.balanceTextTextView.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));
                expensesViewHolder.balanceTextView.setText(balance);
                expensesViewHolder.balanceTextView.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));
            } else {
                expensesViewHolder.balanceTextTextView.setText(R.string.no_debts);
                expensesViewHolder.balanceTextTextView.setTextColor(ContextCompat.getColor(context, R.color.colorSecondaryText));
                expensesViewHolder.balanceTextView.setText("0 " + defaultCurrency);
            }
        }
    }
}
Also used : Expense(com.polito.mad17.madmax.entities.Expense) SharedPreferences(android.content.SharedPreferences) CropCircleTransformation(com.polito.mad17.madmax.entities.CropCircleTransformation)

Example 15 with Expense

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

the class PayExpenseActivity method onOptionsItemSelected.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    Intent intent;
    switch(item.getItemId()) {
        // Respond to the action bar's Up/Home button
        case android.R.id.home:
            Log.d(TAG, "Clicked up button");
            /*
                Intent intent = new Intent(this, GroupDetailActivity.class);
                intent.putExtra("groupID", groupID);
                intent.putExtra("userID", userID);
                startActivity(intent);
                */
            onBackPressed();
            return true;
        case R.id.action_save:
            Log.d(TAG, "Clicked pay expense");
            Double money = null;
            String text = amountEditText.getText().toString();
            if (!text.isEmpty()) {
                try {
                    // it means it is double
                    money = Double.parseDouble(text);
                } catch (Exception e1) {
                    // this means it is not double
                    e1.printStackTrace();
                }
            }
            if (money != null) {
                if (money > debt) {
                    Toast.makeText(PayExpenseActivity.this, getString(R.string.cannot_pay_more), Toast.LENGTH_SHORT).show();
                    return true;
                } else if (money <= 0) {
                    Toast.makeText(PayExpenseActivity.this, getString(R.string.invalid_amount), Toast.LENGTH_SHORT).show();
                    return true;
                } else {
                    Toast.makeText(PayExpenseActivity.this, getString(R.string.paid), Toast.LENGTH_SHORT).show();
                    payDebtForExpense(userID, expenseID, money);
                    // add event for USER_PAY
                    User currentUser = MainActivity.getCurrentUser();
                    String userID = currentUser.getID();
                    Event event = new Event(groupID, Event.EventType.USER_PAY, userID, money + " €");
                    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 = new Intent(this, ExpenseDetailActivity.class);
                    intent.putExtra("groupID", groupID);
                    intent.putExtra("userID", userID);
                    intent.putExtra("expenseID", expenseID);
                    finish();
                    startActivity(intent);
                    return true;
                }
            } else {
                Log.d(TAG, "Error: money is null");
            }
            return true;
    }
    return super.onOptionsItemSelected(item);
}
Also used : User(com.polito.mad17.madmax.entities.User) Event(com.polito.mad17.madmax.entities.Event) Intent(android.content.Intent) SimpleDateFormat(java.text.SimpleDateFormat)

Aggregations

Intent (android.content.Intent)10 DataSnapshot (com.google.firebase.database.DataSnapshot)7 DatabaseError (com.google.firebase.database.DatabaseError)7 ValueEventListener (com.google.firebase.database.ValueEventListener)7 Expense (com.polito.mad17.madmax.entities.Expense)7 User (com.polito.mad17.madmax.entities.User)6 Event (com.polito.mad17.madmax.entities.Event)5 SimpleDateFormat (java.text.SimpleDateFormat)5 View (android.view.View)4 ImageView (android.widget.ImageView)4 HashMap (java.util.HashMap)4 ViewGroup (android.view.ViewGroup)3 TextView (android.widget.TextView)3 MainActivity (com.polito.mad17.madmax.activities.MainActivity)3 CropCircleTransformation (com.polito.mad17.madmax.entities.CropCircleTransformation)3 Group (com.polito.mad17.madmax.entities.Group)3 DecimalFormat (java.text.DecimalFormat)3 Map (java.util.Map)3 SharedPreferences (android.content.SharedPreferences)2 TabLayout (android.support.design.widget.TabLayout)2