Search in sources :

Example 6 with Expense

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

the class PendingExpenseViewAdapter method onBindViewHolder.

@Override
public void onBindViewHolder(final PendingExpenseViewAdapter.ItemExpensesViewHolder holder, int position) {
    if (position == (pendingExpenses.size() - 1)) {
        Log.d(TAG, "item.getKey().equals(\"nullGroup\")");
        holder.imageView.setVisibility(View.GONE);
        holder.nameTextView.setText("");
        holder.groupTextView.setText("");
        holder.yesTextView.setText("");
        holder.noTextView.setText("");
        holder.participantsCountTextView.setText("");
        holder.amountTextView.setText("");
        holder.partecipantsImageView.setVisibility(View.GONE);
        holder.thumbUpButton.setVisibility(View.GONE);
        holder.thumbDownButton.setVisibility(View.GONE);
    } else {
        Expense expense = getItem(position).getValue();
        Log.d(TAG, "item ID " + expense.getID() + " item name " + expense.getDescription());
        String p = expense.getGroupImage();
        Log.d(TAG, "groupImage " + p);
        if (p != null && !p.equals("noImage")) {
            Log.d(TAG, "Image not null " + p);
            Glide.with(layoutInflater.getContext()).load(p).centerCrop().bitmapTransform(new CropCircleTransformation(layoutInflater.getContext())).diskCacheStrategy(DiskCacheStrategy.ALL).into(holder.imageView);
        } else {
            Glide.with(layoutInflater.getContext()).load(R.drawable.group_default).centerCrop().bitmapTransform(new CropCircleTransformation(layoutInflater.getContext())).diskCacheStrategy(DiskCacheStrategy.ALL).into(holder.imageView);
        }
        holder.nameTextView.setText(expense.getDescription());
        holder.groupTextView.setText(expense.getGroupName());
        holder.yesTextView.setText(expense.getYes().toString());
        holder.noTextView.setText(expense.getNo().toString());
        holder.participantsCountTextView.setText(expense.getParticipantsCount().toString());
        holder.imageView.setVisibility(View.VISIBLE);
        holder.partecipantsImageView.setVisibility(View.VISIBLE);
        holder.thumbUpButton.setVisibility(View.VISIBLE);
        holder.thumbDownButton.setVisibility(View.VISIBLE);
        DecimalFormat df = new DecimalFormat("#.##");
        Double amount = expense.getAmount();
        holder.amountTextView.setText(df.format(amount) + " " + expense.getCurrency());
        if (expense.getMyVote().equals("yes")) {
            holder.thumbUpButton.setBackgroundResource(R.drawable.thumb_up_teal);
            holder.thumbDownButton.setBackgroundResource(R.drawable.thumb_down_black);
        } else if (expense.getMyVote().equals("no")) {
            holder.thumbUpButton.setBackgroundResource(R.drawable.thumb_up_black);
            holder.thumbDownButton.setBackgroundResource(R.drawable.thumb_down_amber);
        } else if (expense.getMyVote().equals("null")) {
            holder.thumbUpButton.setBackgroundResource(R.drawable.thumb_up_black);
            holder.thumbDownButton.setBackgroundResource(R.drawable.thumb_down_black);
        }
    }
}
Also used : Expense(com.polito.mad17.madmax.entities.Expense) DecimalFormat(java.text.DecimalFormat) CropCircleTransformation(com.polito.mad17.madmax.entities.CropCircleTransformation)

Example 7 with Expense

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

the class SplitPolicyActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_split_policy);
    // somma quote giĆ  splittate
    totalTextView = (TextView) findViewById(R.id.total);
    // costo della spesa
    amountTextView = (TextView) findViewById(R.id.tv_amount);
    currencyTextView = (TextView) findViewById(R.id.currency);
    currencyAmountTextView = (TextView) findViewById(R.id.currency_amount);
    Intent intent = getIntent();
    amount = intent.getDoubleExtra("amount", 0);
    currency = intent.getStringExtra("currency");
    groupID = intent.getStringExtra("groupID");
    amountsList = (HashMap<String, Double>) intent.getSerializableExtra("participants");
    Log.d(TAG, "I just entered SplitPolicyActivity. amountsList contains: ");
    for (Map.Entry<String, Double> entry : amountsList.entrySet()) {
        Log.d(TAG, entry.getKey() + " " + entry.getValue());
    }
    totalSplit = intent.getDoubleExtra("totalSplit", 0d);
    totalTextView.setText(df.format(totalSplit));
    amountTextView.setText(df.format(amount));
    currencyTextView.setText(currency);
    currencyAmountTextView.setText(currency);
    participants.clear();
    // Retrieve info about members for this expense
    for (final Map.Entry<String, Double> entry : amountsList.entrySet()) {
        databaseReference.child("users").child(entry.getKey()).addListenerForSingleValueEvent(new ValueEventListener() {

            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                User u = new User();
                u.setName(dataSnapshot.child("name").getValue(String.class));
                u.setSurname(dataSnapshot.child("surname").getValue(String.class));
                u.setProfileImage(dataSnapshot.child("image").getValue(String.class));
                u.setSplitPart(entry.getValue());
                u.setExpenseCurrency(currency);
                participants.put(entry.getKey(), u);
                splittersViewAdapter.update(participants);
                splittersViewAdapter.notifyDataSetChanged();
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
            }
        });
    }
    RecyclerView.ItemDecoration divider = new InsetDivider.Builder(SplitPolicyActivity.this).orientation(InsetDivider.VERTICAL_LIST).dividerHeight(getResources().getDimensionPixelSize(R.dimen.divider_height)).color(ContextCompat.getColor(SplitPolicyActivity.this, R.color.colorDivider)).insets(getResources().getDimensionPixelSize(R.dimen.divider_inset), 0).overlay(true).build();
    recyclerView = (RecyclerView) findViewById(R.id.rv_skeleton);
    layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.addItemDecoration(divider);
    splittersViewAdapter = new SplittersViewAdapter(participants, SplitPolicyActivity.this, this);
    recyclerView.setAdapter(splittersViewAdapter);
}
Also used : User(com.polito.mad17.madmax.entities.User) Intent(android.content.Intent) DataSnapshot(com.google.firebase.database.DataSnapshot) LinearLayoutManager(android.support.v7.widget.LinearLayoutManager) DatabaseError(com.google.firebase.database.DatabaseError) RecyclerView(android.support.v7.widget.RecyclerView) ValueEventListener(com.google.firebase.database.ValueEventListener) HashMap(java.util.HashMap) Map(java.util.Map) TreeMap(java.util.TreeMap)

Example 8 with Expense

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

the class GroupExpensesActivity method onCreate.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // setContentView(R.layout.activity_group_expenses);
    final String IDGroup;
    Intent intent = getIntent();
    // if starting activity from itself (adding a new expense)
    if (intent.getBooleanExtra("addExpenseToGroup", true)) {
        IDGroup = intent.getStringExtra("IDGroup");
        String description = intent.getStringExtra("description");
        String amount = intent.getStringExtra("amount");
        String currency = intent.getStringExtra("currency");
        // expenses.put(String.valueOf(i), new Expense(String.valueOf(i), description + " " + currency + " " + amount, (double) i+1));
        Group group = MainActivity.getCurrentUser().getUserGroups().get(IDGroup);
        expenses = group.getExpenses();
    // todo a cosa serve questa expense?? quale utente la fa?
    /*Expense e = new Expense(
                    String.valueOf(expenses.size()), description, null, Double.valueOf(amount),
                    currency, String.valueOf(R.drawable.expense6), "urlBill", false, group.getID(), null, false
            );*/
    // save the new expense
    // expenses.put(String.valueOf(expenses.size()), e);
    // GroupsActivity.users.get(0).addExpense(e);
    // GroupsActivity.myself.addExpense(e);
    // todo mettere addExpenseFirebase
    } else // if starting activity from GroupActivity (tapping on a group for showing details)
    {
        IDGroup = intent.getStringExtra("IDGroup");
        Group group = MainActivity.getCurrentUser().getUserGroups().get(IDGroup);
        expenses = group.getExpenses();
    }
    // then show group expenses list
    // todo getting IDGroup from the intent from GroupsActivity
    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            Intent intent = new Intent(GroupExpensesActivity.this, NewExpenseActivity.class);
            intent.putExtra("IDGroup", IDGroup);
            intent.putExtra("callingActivity", "GroupExpensesActivity");
            intent.putExtra("newPending", false);
            GroupExpensesActivity.this.startActivity(intent);
            finish();
            GroupExpensesActivity.this.startActivity(intent);
        /*Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();*/
        }
    });
    /*        //Button to go to group info
        Button groupInfoButton = (Button) findViewById(R.id.infobutton);
        groupInfoButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view) {

                Context context = GroupExpensesActivity.this;
                Class destinationActivity = GroupInfoActivity.class;
                Intent intent = new Intent(context, destinationActivity);
                intent.putExtra("groupID", IDGroup);
                intent.putExtra("caller", "GroupExpensesActivity");
                startActivity(intent);

            }
        });*/
    // todo when we'll use Firebase -> retrieve expenses HashMap with IDGroup received from GroupsActivity
    ListView lv = (ListView) findViewById(R.id.expenses);
    // for putting data inside the list view I need an adapter
    BaseAdapter a = new BaseAdapter() {

        @Override
        public int getCount() {
            return expenses.size();
        }

        @Override
        public Object getItem(int position) {
            return expenses.get(String.valueOf(position));
        }

        // not changed
        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // if it's the first time I create the view
            if (convertView == null) {
                // LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                LayoutInflater inflater = LayoutInflater.from(GroupExpensesActivity.this);
                // last parameter is very important: for now we don't want to attach our view to the parent view
                convertView = inflater.inflate(R.layout.list_item, parent, false);
            }
            Expense expense = expenses.get(String.valueOf(position));
            ImageView photo = (ImageView) convertView.findViewById(R.id.img_photo);
            TextView description = (TextView) convertView.findViewById(R.id.tv_sender);
            TextView amount = (TextView) convertView.findViewById(R.id.tv_balance);
            if (expense.getExpensePhoto() != null)
                photo.setImageResource(Integer.parseInt(expense.getExpensePhoto()));
            description.setText(expense.getDescription());
            String amountString = expense.getAmount() + " " + expense.getCurrency();
            amount.setText(amountString);
            return convertView;
        }
    };
    lv.setAdapter(a);
}
Also used : ViewGroup(android.view.ViewGroup) Group(com.polito.mad17.madmax.entities.Group) ViewGroup(android.view.ViewGroup) Intent(android.content.Intent) ImageView(android.widget.ImageView) TextView(android.widget.TextView) View(android.view.View) ListView(android.widget.ListView) ListView(android.widget.ListView) Expense(com.polito.mad17.madmax.entities.Expense) NewExpenseActivity(com.polito.mad17.madmax.activities.expenses.NewExpenseActivity) LayoutInflater(android.view.LayoutInflater) FloatingActionButton(android.support.design.widget.FloatingActionButton) TextView(android.widget.TextView) ImageView(android.widget.ImageView) BaseAdapter(android.widget.BaseAdapter)

Example 9 with Expense

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

the class GroupsViewAdapter method onBindViewHolder.

@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
    final ItemGroupViewHolder groupViewHolder = (ItemGroupViewHolder) holder;
    Map.Entry<String, Group> item = getItem(position);
    if (position == (mData.size() - 1)) {
        Log.d(TAG, "item.getKey().equals(\"nullGroup\")");
        groupViewHolder.imageView.setVisibility(View.GONE);
        groupViewHolder.nameTextView.setText("");
        groupViewHolder.balanceTextTextView.setText("");
        groupViewHolder.balanceTextView.setText("");
    } else {
        Log.d(TAG, "item ID " + item.getKey() + " item name " + item.getValue().getName());
        // String p = groups.get(String.valueOf(position)).getImage();
        groupViewHolder.imageView.setVisibility(View.VISIBLE);
        String p = item.getValue().getImage();
        if (p != null && !p.equals("noImage")) {
            Log.d(TAG, "Image not null " + p);
            Glide.with(layoutInflater.getContext()).load(p).centerCrop().bitmapTransform(new CropCircleTransformation(layoutInflater.getContext())).diskCacheStrategy(DiskCacheStrategy.ALL).into(groupViewHolder.imageView);
        } else {
            Glide.with(layoutInflater.getContext()).load(R.drawable.group_default).centerCrop().bitmapTransform(new CropCircleTransformation(layoutInflater.getContext())).diskCacheStrategy(DiskCacheStrategy.ALL).into(groupViewHolder.imageView);
        }
        groupViewHolder.nameTextView.setText(item.getValue().getName());
        // mydebt = mio debito con il gruppo
        String groupname = item.getValue().getName();
        totBalances = item.getValue().getCurrencyBalances();
        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
        String defaultCurrency = sharedPref.getString(SettingsFragment.DEFAULT_CURRENCY, "");
        Boolean multipleCurrencies = false;
        Double shownBal;
        String shownCurr;
        if (groupname.equals("fff") || groupname.equals("Regalo")) {
            Log.d(TAG, "sii");
        }
        Log.d(TAG, "callingActivity " + callingActivity);
        if (!callingActivity.equals("FriendDetailActivity") && !callingActivity.equals("ChooseGroupActivity")) {
            if (totBalances != null) {
                groupViewHolder.balanceTextTextView.setVisibility(View.VISIBLE);
                groupViewHolder.balanceTextView.setVisibility(View.VISIBLE);
                for (Map.Entry<String, Double> entry : totBalances.entrySet()) {
                    Log.d(TAG, "Bilancio in " + groupname + " : " + entry.getValue() + " " + entry.getKey());
                }
                if (!totBalances.isEmpty()) {
                    // If there is more than one currency
                    if (totBalances.size() > 1) {
                        multipleCurrencies = true;
                    } else // If there is just one currency
                    {
                        multipleCurrencies = false;
                    }
                    if (totBalances.containsKey(defaultCurrency)) {
                        shownBal = totBalances.get(defaultCurrency);
                        shownCurr = defaultCurrency;
                    } else {
                        shownCurr = (String) totBalances.keySet().toArray()[0];
                        shownBal = totBalances.get(shownCurr);
                    }
                    // Print balance
                    if (shownBal > 0) {
                        groupViewHolder.balanceTextTextView.setText(R.string.you_should_receive);
                        groupViewHolder.balanceTextTextView.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));
                        if (multipleCurrencies)
                            groupViewHolder.balanceTextView.setText(df.format(shownBal) + " " + shownCurr + "*");
                        else
                            groupViewHolder.balanceTextView.setText(df.format(shownBal) + " " + shownCurr);
                        groupViewHolder.balanceTextView.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));
                    } else if (shownBal < 0) {
                        groupViewHolder.balanceTextTextView.setText(R.string.you_owe);
                        groupViewHolder.balanceTextTextView.setTextColor(ContextCompat.getColor(context, R.color.colorPrimaryDark));
                        if (multipleCurrencies)
                            groupViewHolder.balanceTextView.setText(df.format(Math.abs(shownBal)) + " " + shownCurr + "*");
                        else
                            groupViewHolder.balanceTextView.setText(df.format(Math.abs(shownBal)) + " " + shownCurr);
                        groupViewHolder.balanceTextView.setTextColor(ContextCompat.getColor(context, R.color.colorPrimaryDark));
                    } else if (shownBal == 0) {
                        groupViewHolder.balanceTextTextView.setText(R.string.no_debts);
                        groupViewHolder.balanceTextTextView.setTextColor(ContextCompat.getColor(context, R.color.colorSecondaryText));
                        groupViewHolder.balanceTextView.setText("0 " + defaultCurrency);
                        groupViewHolder.balanceTextView.setTextColor(ContextCompat.getColor(context, R.color.colorSecondaryText));
                    }
                }
                groupViewHolder.balanceTextTextView.setVisibility(View.VISIBLE);
                groupViewHolder.balanceTextView.setVisibility(View.VISIBLE);
            } else // If there are no balances in the map
            {
                groupViewHolder.balanceTextTextView.setText(R.string.no_debts);
                groupViewHolder.balanceTextTextView.setTextColor(ContextCompat.getColor(context, R.color.colorSecondaryText));
                groupViewHolder.balanceTextView.setText("0 " + defaultCurrency);
                groupViewHolder.balanceTextView.setTextColor(ContextCompat.getColor(context, R.color.colorSecondaryText));
                groupViewHolder.balanceTextTextView.setVisibility(View.VISIBLE);
                groupViewHolder.balanceTextView.setVisibility(View.VISIBLE);
            }
        }
        if (callingActivity.equals(DetailFragment.class.getSimpleName())) {
            groupViewHolder.balanceTextTextView.setVisibility(View.GONE);
            groupViewHolder.balanceTextView.setVisibility(View.GONE);
        }
    /*
            else
            {
                groupViewHolder.balanceTextTextView.setVisibility(View.GONE);
                groupViewHolder.balanceTextView.setVisibility(View.GONE);
            }
            */
    // check if there are expenses with other currencies than the default
    /*Boolean defaultCurrencyExpense = false;
            Boolean otherCurrenciesPresent = false;
            Double groupBalanceDefaultCurrency = 0.0d;
            HashMap<String, Double> otherCurrenciesBalance = new HashMap<>();

            HashMap<String, Expense> groupExpenses = item.getValue().getExpenses();

            if(groupExpenses != null) {
                for (Map.Entry<String, Expense> expenseEntry : groupExpenses.entrySet()) {
                    String currentCurrency = expenseEntry.getValue().getCurrency();

                    if (currentCurrency.equals(defaultCurrency)) {
                        groupBalanceDefaultCurrency += expenseEntry.getValue().getAmount();
                        defaultCurrencyExpense = true;
                    } else {
                        otherCurrenciesPresent = true;
                        if (otherCurrenciesBalance.containsKey(currentCurrency)) {
                            Double currentBalance = otherCurrenciesBalance.get(currentCurrency);
                            currentBalance += otherCurrenciesBalance.get(currentCurrency);
                            otherCurrenciesBalance.put(currentCurrency, currentBalance);
                        } else {
                            otherCurrenciesBalance.put(currentCurrency, expenseEntry.getValue().getAmount());
                        }
                    }
                }

                if (defaultCurrencyExpense) {
                    if (groupBalanceDefaultCurrency == null) {
                        groupViewHolder.balanceTextTextView.setText("");
                        groupViewHolder.balanceTextView.setText("");
                        return;
                    }

                    if (groupBalanceDefaultCurrency > 0) {
                        groupViewHolder.balanceTextTextView.setText(R.string.credit_of);
                        groupViewHolder.balanceTextTextView.setTextColor(ContextCompat.getColor(context, R.color.colorPrimaryDark));

                        String balance = df.format(Math.abs(groupBalanceDefaultCurrency)) + " " + defaultCurrency;
                        if (otherCurrenciesPresent) {
                            balance += " *";
                        }

                        groupViewHolder.balanceTextView.setText(balance);
                        groupViewHolder.balanceTextView.setTextColor(ContextCompat.getColor(context, R.color.colorPrimaryDark));
                    } else {
                        if (groupBalanceDefaultCurrency < 0) {
                            groupViewHolder.balanceTextTextView.setText(R.string.debt_of);
                            groupViewHolder.balanceTextTextView.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));

                            String balance = df.format(Math.abs(groupBalanceDefaultCurrency)) + " " + defaultCurrency;
                            if (otherCurrenciesPresent) {
                                balance += " *";
                            }

                            groupViewHolder.balanceTextView.setText(balance);
                            groupViewHolder.balanceTextView.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));
                        } else if (!otherCurrenciesPresent) {
                            groupViewHolder.balanceTextTextView.setText(R.string.no_debts);
                            groupViewHolder.balanceTextTextView.setTextColor(ContextCompat.getColor(context, R.color.colorSecondaryText));
                            groupViewHolder.balanceTextView.setText("0.0 " + defaultCurrency);
                            groupViewHolder.balanceTextView.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));
                        } else {
                            Map.Entry<String, Double> entry = otherCurrenciesBalance.entrySet().iterator().next();

                            if (entry.getValue() > 0) {
                                groupViewHolder.balanceTextTextView.setText(R.string.credit_of);
                                groupViewHolder.balanceTextTextView.setTextColor(ContextCompat.getColor(context, R.color.colorPrimaryDark));

                                String balance = df.format(Math.abs(entry.getValue())) + " " + entry.getKey();

                                groupViewHolder.balanceTextView.setText(balance);
                                groupViewHolder.balanceTextView.setTextColor(ContextCompat.getColor(context, R.color.colorPrimaryDark));
                            } else {
                                groupViewHolder.balanceTextTextView.setText(R.string.debt_of);
                                groupViewHolder.balanceTextTextView.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));

                                String balance = df.format(Math.abs(entry.getValue())) + " " + entry.getKey();

                                groupViewHolder.balanceTextView.setText(balance);
                                groupViewHolder.balanceTextView.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));
                            }
                        }
                    }
                }
            }
            else
            {
                groupViewHolder.balanceTextTextView.setText(R.string.no_debts);
                groupViewHolder.balanceTextTextView.setTextColor(ContextCompat.getColor(context, R.color.colorSecondaryText));
                groupViewHolder.balanceTextView.setText("0.0 " + defaultCurrency);
                groupViewHolder.balanceTextView.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));
            }*/
    }
}
Also used : ViewGroup(android.view.ViewGroup) Group(com.polito.mad17.madmax.entities.Group) SharedPreferences(android.content.SharedPreferences) CropCircleTransformation(com.polito.mad17.madmax.entities.CropCircleTransformation) DetailFragment(com.polito.mad17.madmax.activities.DetailFragment) HashMap(java.util.HashMap) Map(java.util.Map)

Example 10 with Expense

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

the class ExpenseDetailActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_expense_detail);
    Intent intent = getIntent();
    groupID = intent.getStringExtra("groupID");
    userID = intent.getStringExtra("userID");
    expenseID = intent.getStringExtra("expenseID");
    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());
            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);
    // Set data of upper part of Activity
    imageView = (ImageView) findViewById(R.id.img_photo);
    amountTextView = (TextView) findViewById(R.id.tv_amount);
    creatorNameTextView = (TextView) findViewById(R.id.tv_creator_name);
    expenseNameTextView = (TextView) findViewById(R.id.tv_pending_name);
    balanceTextTextView = (TextView) findViewById(R.id.tv_balance_text);
    balanceTextView = (TextView) findViewById(R.id.tv_balance);
    payExpenseButton = (Button) findViewById(R.id.btn_pay_debt);
    userImage = MainActivity.getCurrentUser().getProfileImage();
    payExpenseButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Log.d(TAG, "Clicked payButton");
            if (expenseBalance >= 0) {
                Toast.makeText(ExpenseDetailActivity.this, getString(R.string.no_debts_to_pay_for_expense), Toast.LENGTH_SHORT).show();
            } else {
                Intent intent = new Intent(ExpenseDetailActivity.this, PayExpenseActivity.class);
                intent.putExtra("groupID", groupID);
                intent.putExtra("userID", userID);
                intent.putExtra("userImage", userImage);
                intent.putExtra("debt", expenseBalance);
                intent.putExtra("expenseID", expenseID);
                intent.putExtra("expenseName", expenseName);
                intent.putExtra("expenseCurrency", currency);
                intent.putExtra("expenseImage", expensePhoto);
                startActivity(intent);
                finish();
            }
        }
    });
    // Retrieve data of this expense
    databaseReference.child("expenses").child(expenseID).addListenerForSingleValueEvent(new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            expenseName = dataSnapshot.child("description").getValue(String.class);
            Double amount = dataSnapshot.child("amount").getValue(Double.class);
            currency = dataSnapshot.child("currency").getValue(String.class);
            expensePhoto = dataSnapshot.child("expensePhoto").getValue(String.class);
            expenseNameTextView.setText(expenseName);
            // .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);
            DecimalFormat df = new DecimalFormat("#.##");
            amountTextView.setText(df.format(amount) + " " + currency);
            // Retrieve my balance for this expense
            Double dueImport = Double.parseDouble(String.valueOf(dataSnapshot.child("participants").child(userID).child("fraction").getValue())) * dataSnapshot.child("amount").getValue(Double.class);
            Double alreadyPaid = dataSnapshot.child("participants").child(userID).child("alreadyPaid").getValue(Double.class);
            expenseBalance = alreadyPaid - dueImport;
            expenseBalance = Math.floor(expenseBalance * 100) / 100;
            if (expenseBalance > 0) {
                balanceTextTextView.setText("For this expense you should receive");
                balanceTextView.setText(expenseBalance.toString() + " " + currency);
            } else if (expenseBalance < 0) {
                balanceTextTextView.setText("For this expense you should pay");
                Double absBalance = abs(expenseBalance);
                balanceTextView.setText(absBalance.toString() + " " + currency);
            } else if (expenseBalance == 0) {
                balanceTextTextView.setText("For this expense you have no debts");
                balanceTextView.setText("0" + " " + currency);
            }
            // Retrieve name and surname of creator
            String creatorID = dataSnapshot.child("creatorID").getValue(String.class);
            databaseReference.child("users").child(creatorID).addListenerForSingleValueEvent(new ValueEventListener() {

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

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

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
}
Also used : DecimalFormat(java.text.DecimalFormat) ExpenseDetailPagerAdapter(com.polito.mad17.madmax.activities.ExpenseDetailPagerAdapter) Intent(android.content.Intent) DataSnapshot(com.google.firebase.database.DataSnapshot) ImageView(android.widget.ImageView) View(android.view.View) TextView(android.widget.TextView) DatabaseError(com.google.firebase.database.DatabaseError) TabLayout(android.support.design.widget.TabLayout) ValueEventListener(com.google.firebase.database.ValueEventListener) ActionBar(android.support.v7.app.ActionBar)

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