Search in sources :

Example 46 with DatabaseError

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

the class BarDetailFragment method onCreateView.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    mainView = inflater.inflate(R.layout.fragment_bar_detail, container, false);
    imageView = (ImageView) mainView.findViewById(R.id.img_photo);
    nameTextView = (TextView) mainView.findViewById(R.id.tv_bar_name);
    emailTextView = (TextView) mainView.findViewById(R.id.tv_email);
    balanceLayout = (RelativeLayout) mainView.findViewById(R.id.lv_balance_layout);
    balanceTextView = (TextView) mainView.findViewById(R.id.tv_balance_text);
    balanceView = (TextView) mainView.findViewById(R.id.tv_balance);
    payButton = (Button) mainView.findViewById(R.id.btn_pay_debt);
    initCollapsingToolbar();
    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this.getContext());
    defaultCurrency = sharedPref.getString(SettingsFragment.DEFAULT_CURRENCY, "");
    // Extract data from bundle
    Bundle bundle = this.getArguments();
    if (activityName.equals("FriendDetailActivity")) {
        if (bundle != null) {
            payButton.setVisibility(View.GONE);
            // Extract data from bundle
            friendID = bundle.getString("friendID");
            // Show data of friend
            databaseReference.child("users").child(friendID).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);
                    String email = dataSnapshot.child("email").getValue(String.class);
                    nameTextView.setText(name + " " + surname);
                    emailTextView.setText(email);
                    // Loading profile image
                    String photo = dataSnapshot.child("image").getValue(String.class);
                    if (photo != null) {
                        Glide.with(getActivity()).load(photo).centerCrop().diskCacheStrategy(DiskCacheStrategy.ALL).into(imageView);
                    } else {
                        Glide.with(getActivity()).load(R.drawable.user_default).centerCrop().diskCacheStrategy(DiskCacheStrategy.ALL).into(imageView);
                    }
                    balanceLayout.setVisibility(View.GONE);
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                }
            });
        }
    } else if (activityName.equals("GroupDetailActivity")) {
        if (bundle != null) {
            // Extract data from bundle
            groupID = bundle.getString("groupID");
            userID = bundle.getString("userID");
            setInterface((OnItemClickInterface) getActivity());
            payButton.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    Log.d(TAG, "Clicked payButton");
                    // Suppongo di non avere debiti in nessuna valuta
                    Boolean mustPay = false;
                    String currency = null;
                    // Se ho debiti in anche una sola valuta, allora posso entrare nella PayGroupActivity
                    for (Map.Entry<String, Double> entry : totBalances.entrySet()) {
                        if (entry.getValue() < 0) {
                            mustPay = true;
                            currency = entry.getKey();
                        }
                    }
                    // Se ho debiti in almeno una valuta
                    if (mustPay) {
                        Intent intent = new Intent(getActivity(), PayGroupActivity.class);
                        intent.putExtra("groupID", groupID);
                        intent.putExtra("userID", userID);
                        intent.putExtra("totBalances", totBalances);
                        intent.putExtra("shownCurrency", currency);
                        intent.putExtra("groupName", groupName);
                        intent.putExtra("groupImage", image);
                        startActivity(intent);
                    } else // Se non ho debiti in nessuna valuta
                    {
                        Toast.makeText(getActivity(), getString(R.string.no_debts_to_pay), Toast.LENGTH_SHORT).show();
                    }
                }
            });
            balanceView.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    Log.d(TAG, "Clicked balance");
                    Intent intent = new Intent(getActivity(), BalancesActivity.class);
                    intent.putExtra("balances", totBalances);
                    intent.putExtra("groupID", groupID);
                    startActivity(intent);
                }
            });
            // retrieve data of group
            groupListener = databaseReference.child("groups").child(groupID).addValueEventListener(new ValueEventListener() {

                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    if (!listenedGroup)
                        listenedGroup = true;
                    // totBalance = 0d;
                    totBalances.clear();
                    // Retrieve group name
                    groupName = dataSnapshot.child("name").getValue(String.class);
                    if (groupName != null)
                        nameTextView.setText(groupName);
                    // Retrieve group image
                    image = dataSnapshot.child("image").getValue(String.class);
                    if (image != null && !image.equals("noImage")) {
                        Log.d(TAG, "Nome gruppo: " + dataSnapshot.child("name").getValue(String.class) + "  Immagine: " + image);
                        // Loading group image into bar
                        Glide.with(getActivity()).load(dataSnapshot.child("image").getValue(String.class)).centerCrop().diskCacheStrategy(DiskCacheStrategy.ALL).into(imageView);
                    } else {
                        Log.d(TAG, "Nome gruppo: " + dataSnapshot.child("name").getValue(String.class) + "  Immagine di default");
                        // Loading group image into bar
                        Glide.with(getActivity()).load(R.drawable.group_default).centerCrop().diskCacheStrategy(DiskCacheStrategy.ALL).into(imageView);
                    }
                    // Retrieve group balances in all currencies
                    for (DataSnapshot groupExpenseSnapshot : dataSnapshot.child("expenses").getChildren()) {
                        // Se la spesa non è stata eliminata
                        if (groupExpenseSnapshot.getValue(Boolean.class) == true) {
                            // Ascolto la singola spesa del gruppo
                            final String expenseID = groupExpenseSnapshot.getKey();
                            Log.d(TAG, "considero la spesa " + expenseID);
                            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()) {
                                        if (participantSnapshot.getKey().equals(userID))
                                            involved = true;
                                    }
                                    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
                                        Double alreadyPaid = dataSnapshot.child("participants").child(userID).child("alreadyPaid").getValue(Double.class);
                                        Double dueImport = dataSnapshot.child("participants").child(userID).child("fraction").getValue(Double.class) * dataSnapshot.child("amount").getValue(Double.class);
                                        Double balance = alreadyPaid - dueImport;
                                        String currency = dataSnapshot.child("currency").getValue(String.class);
                                        // current balance for that currency
                                        Double temp = totBalances.get(currency);
                                        // update balance for that currency
                                        if (temp != null) {
                                            totBalances.put(currency, temp + balance);
                                        } else {
                                            totBalances.put(currency, balance);
                                        }
                                        // se user per quella spesa ha già pagato più soldi della sua quota, il balance è positivo
                                        // totBalance += balance;
                                        Boolean multipleCurrencies = false;
                                        balanceLayout.setVisibility(View.VISIBLE);
                                        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) {
                                                balanceTextView.setText(R.string.you_should_receive);
                                                if (multipleCurrencies)
                                                    balanceView.setText(df.format(shownBal) + " " + shownCurr + "*");
                                                else
                                                    balanceView.setText(df.format(shownBal) + " " + shownCurr);
                                            } else if (shownBal < 0) {
                                                balanceTextView.setText(R.string.you_owe);
                                                if (multipleCurrencies)
                                                    balanceView.setText(df.format(Math.abs(shownBal)) + " " + shownCurr + "*");
                                                else
                                                    balanceView.setText(df.format(Math.abs(shownBal)) + " " + shownCurr);
                                            } else if (shownBal == 0) {
                                                balanceTextView.setText(R.string.no_debts);
                                                balanceView.setText("0 " + defaultCurrency);
                                            }
                                        } else // If there are no balances in the map
                                        {
                                            balanceTextView.setText(R.string.no_debts);
                                            balanceView.setText("0 " + defaultCurrency);
                                        }
                                        Log.d(TAG, "sono coinvolto nella spesa " + expenseID + ", dovevo " + dueImport + ", ho dato " + alreadyPaid);
                                    }
                                }

                                @Override
                                public void onCancelled(DatabaseError databaseError) {
                                    balanceTextView.setText("Balance not available");
                                    balanceLayout.setVisibility(View.VISIBLE);
                                }
                            });
                        }
                    }
                // Ora ho finito di calcolare i bilanci
                /*
                        if(totBalance<0)
                            balanceTextView.setText(getString(R.string.negative_balance));
                        else
                            balanceTextView.setText(getString(R.string.positive_balance));
                            */
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    availableGroupData = false;
                }
            });
        }
    }
    return mainView;
}
Also used : SharedPreferences(android.content.SharedPreferences) Bundle(android.os.Bundle) 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) ValueEventListener(com.google.firebase.database.ValueEventListener) HashMap(java.util.HashMap) Map(java.util.Map)

Example 47 with DatabaseError

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

the class DetailFragment method onCreateView.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // create the view to return
    View mainView = null;
    // get the bundle
    Bundle bundle = this.getArguments();
    // the listener will be the GroupDetailActivity or the FriendDetailActivity
    setInterface((OnItemClickInterface) getActivity());
    databaseReference = FirebaseDatabase.getInstance().getReference();
    // when an item in the list will be clicked the onListItemClicked will be called
    groupsViewAdapter = new GroupsViewAdapter(this.getContext(), this, groups, DetailFragment.TAG);
    if (activityName.equals("FriendDetailActivity")) {
        Log.d(TAG, "FriendDetailActivity per RecylerView");
        // Inflate the layout for this fragment
        mainView = inflater.inflate(R.layout.skeleton_list_friend, container, false);
        RecyclerView.ItemDecoration divider = new InsetDivider.Builder(getContext()).orientation(InsetDivider.VERTICAL_LIST).dividerHeight(getResources().getDimensionPixelSize(R.dimen.divider_height)).color(ContextCompat.getColor(getContext(), R.color.colorDivider)).insets(getResources().getDimensionPixelSize(R.dimen.divider_inset), 0).overlay(true).build();
        recyclerView = (RecyclerView) mainView.findViewById(R.id.rv_skeleton);
        layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(divider);
        recyclerView.setAdapter(groupsViewAdapter);
        // Extract data from bundle
        friendID = bundle.getString("friendID");
        // Show shared groups
        databaseReference.child("users").child(MainActivity.getCurrentUser().getID()).child("friends").child(friendID).child("sharedGroups").addListenerForSingleValueEvent(new ValueEventListener() {

            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot sharedGroupSnapshot : dataSnapshot.getChildren()) {
                    FirebaseUtils.getInstance().getGroup(sharedGroupSnapshot.getKey(), groups, groupsViewAdapter);
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
            }
        });
    } else if (activityName.equals("GroupDetailActivity")) {
        groupID = bundle.getString("groupID");
        mainView = inflater.inflate(R.layout.fragment_group_detail, container, false);
        fab = (FloatingActionButton) getActivity().findViewById(R.id.fab);
        fab.setImageResource(android.R.drawable.ic_input_add);
        TabLayout tabLayout = (TabLayout) mainView.findViewById(R.id.tab_layout);
        tabLayout.addTab(tabLayout.newTab().setText(R.string.expenses));
        tabLayout.addTab(tabLayout.newTab().setText(R.string.members));
        tabLayout.addTab(tabLayout.newTab().setText(R.string.activities));
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
        updateFab(0);
        final ViewPager viewPager = (ViewPager) mainView.findViewById(R.id.main_view_pager);
        final DetailFragment.PagerAdapter adapter = new DetailFragment.PagerAdapter(getActivity().getSupportFragmentManager(), tabLayout.getTabCount());
        viewPager.setAdapter(adapter);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

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

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

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
    }
    return mainView;
}
Also used : GroupsViewAdapter(com.polito.mad17.madmax.activities.groups.GroupsViewAdapter) Bundle(android.os.Bundle) LinearLayoutManager(android.support.v7.widget.LinearLayoutManager) DataSnapshot(com.google.firebase.database.DataSnapshot) View(android.view.View) RecyclerView(android.support.v7.widget.RecyclerView) ViewPager(android.support.v4.view.ViewPager) FragmentPagerAdapter(android.support.v4.app.FragmentPagerAdapter) DatabaseError(com.google.firebase.database.DatabaseError) TabLayout(android.support.design.widget.TabLayout) FloatingActionButton(android.support.design.widget.FloatingActionButton) RecyclerView(android.support.v7.widget.RecyclerView) ValueEventListener(com.google.firebase.database.ValueEventListener)

Example 48 with DatabaseError

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

the class PayGroupActivity method payDebtForExpenses.

// money = cifra che ho a disposizione per ripianare i debiti (solo in una certa valuta!!)
void payDebtForExpenses(final String userID, String groupID, Double money, final String currency) {
    myMoney = money;
    Log.d(TAG, "here in payDebtForExpenses");
    databaseReference.child("groups").child(groupID).addListenerForSingleValueEvent(new ValueEventListener() {

        @Override
        public void onDataChange(final DataSnapshot groupDataSnapshot) {
            final Boolean deleted = groupDataSnapshot.child("deleted").getValue(Boolean.class);
            // If group has not been deleted (should be useless here)
            if (deleted != null) {
                for (DataSnapshot groupExpenseSnapshot : groupDataSnapshot.child("expenses").getChildren()) {
                    // Se ho ancora soldi per ripagare le spese
                    if (myMoney > 0) {
                        Log.d(TAG, "myMoney " + myMoney);
                        // Considero 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
                            final String expenseID = groupExpenseSnapshot.getKey();
                            Log.d(TAG, "ripangando la spesa " + expenseID);
                            databaseReference.child("expenses").child(expenseID).addListenerForSingleValueEvent(new ValueEventListener() {

                                @Override
                                public void onDataChange(DataSnapshot dataSnapshot) {
                                    // I can use money only to pay expenses in the currency of money!!
                                    if (dataSnapshot.child("currency").getValue(String.class).equals(currency)) {
                                        String creatorID = dataSnapshot.child("creatorID").getValue(String.class);
                                        Double alreadyPaidByCreator = dataSnapshot.child("participants").child(creatorID).child("alreadyPaid").getValue(Double.class);
                                        // 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) {
                                            // alreadyPaid = soldi già messi dallo user per quella spesa
                                            // dueImport = quota che user deve mettere per quella spesa
                                            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 amount = dataSnapshot.child("amount").getValue(Double.class);
                                            Double dueImport = Double.parseDouble(String.valueOf(dataSnapshot.child("participants").child(userID).child("fraction").getValue())) * amount;
                                            Double stillToPay = dueImport - alreadyPaid;
                                            // Se questa spesa non è già stata ripagata in toto
                                            if (stillToPay > 0) {
                                                // Se ho ancora abbastanza soldi per ripagare in toto questa spesa, la ripago in toto AL CREATOR!!
                                                if (myMoney >= stillToPay) {
                                                    // Quota già pagata DA ME per questa spesa aumenta
                                                    databaseReference.child("expenses").child(expenseID).child("participants").child(userID).child("alreadyPaid").setValue(dueImport);
                                                    // Quota già pagata DAL CREATOR per questa spesa diminuisce, perchè gli sto dando dei soldi
                                                    databaseReference.child("expenses").child(expenseID).child("participants").child(creatorID).child("alreadyPaid").setValue(alreadyPaidByCreator - stillToPay);
                                                    // Adesso ho meno soldi a disposizione, perchè li ho usati in parte per ripagare questa spesa
                                                    myMoney -= stillToPay;
                                                } else // Altrimenti la ripago solo in parte
                                                {
                                                    databaseReference.child("expenses").child(expenseID).child("participants").child(userID).child("alreadyPaid").setValue(alreadyPaid + myMoney);
                                                    databaseReference.child("expenses").child(expenseID).child("participants").child(creatorID).child("alreadyPaid").setValue(alreadyPaidByCreator - myMoney);
                                                    myMoney = 0d;
                                                }
                                            }
                                        }
                                    }
                                }

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

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
}
Also used : DatabaseError(com.google.firebase.database.DatabaseError) ValueEventListener(com.google.firebase.database.ValueEventListener) DataSnapshot(com.google.firebase.database.DataSnapshot)

Example 49 with DatabaseError

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

the class FriendsFragment method getUserAndGroupBalance.

// Retrieve balance of userID toward groupID
void getUserAndGroupBalance(final String userID, final String name, final String surname, final String profileImage, final String groupID) {
    // key = currency
    // value = balance for that currency
    final HashMap<String, Double> totBalances = new HashMap<>();
    totBalances.clear();
    // retrieve data of group
    // final HashMap<String, Double> totalBalance = new HashMap<>();
    // totalBalance.put(userID,0d);
    totBalance = 0d;
    groupListener = databaseReference.child("groups").child(groupID).addValueEventListener(new ValueEventListener() {

        @Override
        public void onDataChange(final DataSnapshot groupDataSnapshot) {
            totBalances.clear();
            // totalBalance.put(userID,0d);
            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) {
                final User u = new User();
                u.setName(name);
                u.setSurname(surname);
                u.setProfileImage(profileImage);
                u.setBalancesWithGroup(totBalances);
                // Metto subito user nella lista, con bilanci inizialmente a zero
                if (!deleted && groupDataSnapshot.child("members").hasChild(MainActivity.getCurrentUID()) && !groupDataSnapshot.child("members").child(MainActivity.getCurrentUID()).child("deleted").getValue(Boolean.class)) {
                    friends.put(userID, u);
                } else {
                    friends.remove(userID);
                }
                friendsViewAdapter.update(friends);
                friendsViewAdapter.notifyDataSetChanged();
                // Se gruppo ha almeno una spesa
                if (groupDataSnapshot.child("expenses").getChildrenCount() > 0) {
                    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);
                                        Double fraction = dataSnapshot.child("participants").child(userID).child("fraction").getValue(Double.class);
                                        Double balance = null;
                                        String currency = null;
                                        if (fraction != null) {
                                            Log.d(TAG, "Fraction: " + fraction);
                                            Double amount = dataSnapshot.child("amount").getValue(Double.class);
                                            if (amount != null) {
                                                Double dueImport = fraction * amount;
                                                balance = alreadyPaid - dueImport;
                                                currency = dataSnapshot.child("currency").getValue(String.class);
                                            // se user per quella spesa ha già pagato più soldi della sua quota, il balance è positivo
                                            }
                                        }
                                        if (balance != null && currency != null) {
                                            // 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);
                                            }
                                        // se user per quella spesa ha già pagato più soldi della sua quota, il balance è positivo
                                        // Double currentBalance = totBalances.get(userID);
                                        // totBalances.put(userID, currentBalance+balance);
                                        }
                                    }
                                    // u.setBalanceWithGroup(totalBalance.get(userID));
                                    u.setBalancesWithGroup(totBalances);
                                    u.setName(name);
                                    u.setSurname(surname);
                                    u.setProfileImage(profileImage);
                                    // 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)) {
                                        friends.put(userID, u);
                                    } else {
                                        friends.remove(userID);
                                    }
                                    friendsViewAdapter.update(friends);
                                    friendsViewAdapter.notifyDataSetChanged();
                                }

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

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

Example 50 with DatabaseError

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

the class NewMemberActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    Log.d(TAG, "onCreate di NewMemeberAcitivity");
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_new_member);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    buttonInvite = (Button) findViewById(R.id.btn_new_friend);
    Intent intent = getIntent();
    groupID = intent.getStringExtra("groupID");
    groupName = intent.getStringExtra("groupName");
    Log.d(TAG, groupID);
    friendsListView = (ListView) findViewById(R.id.lv_friends);
    friendsAdapter = new HashMapFriendsAdapter(friends);
    addedFriendsListView = (ListView) findViewById(R.id.lv_added_members);
    addedAdapter = new HashMapFriendsAdapter(alreadySelected);
    addedFriendsListView.setAdapter(addedAdapter);
    databaseReference.child("users").child(MainActivity.getCurrentUID()).child("friends").addListenerForSingleValueEvent(new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Boolean alreadyAdded = false;
            for (DataSnapshot friendSnapshot : dataSnapshot.getChildren()) {
                if (friendSnapshot.hasChild("sharedGroups")) {
                    if (friendSnapshot.child("sharedGroups").hasChild(groupID)) {
                        alreadyAdded = friendSnapshot.child("sharedGroups").child(groupID).getValue(Boolean.class);
                    }
                }
                // se sono già nel gruppo => vengono inseriti nell'addedAdapter
                if (alreadyAdded) {
                    FirebaseUtils.getInstance().getFriendInviteToGroup(friendSnapshot.getKey(), groupID, alreadySelected, addedAdapter);
                } else // altrimenti vengono inseriti nella lista friendsAdapter degli amici disponibili
                {
                    FirebaseUtils.getInstance().getFriendInviteToGroup(friendSnapshot.getKey(), "", friends, friendsAdapter);
                }
            }
            friendsListView.setAdapter(friendsAdapter);
            addedFriendsListView.setAdapter(addedAdapter);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.w(TAG, databaseError.getMessage());
        }
    });
    // When i click on one friend of the list
    friendsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            User item = friendsAdapter.getItem(position).getValue();
            friends.remove(item.getID());
            friendsAdapter.update(friends);
            friendsAdapter.notifyDataSetChanged();
            alreadySelected.put(item.getID(), item);
            addedAdapter.update(alreadySelected);
            addedAdapter.notifyDataSetChanged();
        }
    });
    // When i click on one added friend of the list
    addedFriendsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            User item = addedAdapter.getItem(position).getValue();
            alreadySelected.remove(item.getID());
            addedAdapter.update(alreadySelected);
            addedAdapter.notifyDataSetChanged();
            friends.put(item.getID(), item);
            friendsAdapter.update(friends);
            friendsAdapter.notifyDataSetChanged();
        }
    });
    buttonInvite.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Log.d(TAG, "button clicked");
            Log.d(TAG, "invite a member to join the group");
            // String deepLink = getString(R.string.invitation_deep_link) + "?groupToBeAddedID=" + groupID+ "?inviterToGroupUID=" + MainActivity.getCurrentUID();
            Uri.Builder builder = Uri.parse(getString(R.string.invitation_deep_link)).buildUpon().appendQueryParameter("groupToBeAddedID", groupID).appendQueryParameter("inviterID", MainActivity.getCurrentUID());
            Intent intent = new AppInviteInvitation.IntentBuilder(getString(R.string.invitation_title)).setDeepLink(builder.build()).setMessage(// .setCustomImage(Uri.parse(getString(R.string.invitation_custom_image)))
            getString(R.string.invitationToGroup_message)).setCallToActionText(// todo vedere perchè non mostra questo link
            getString(R.string.invitationToGroup)).build();
            startActivityForResult(intent, MainActivity.REQUEST_INVITE_GROUP);
        }
    });
}
Also used : User(com.polito.mad17.madmax.entities.User) AppInviteInvitation(com.google.android.gms.appinvite.AppInviteInvitation) Intent(android.content.Intent) DataSnapshot(com.google.firebase.database.DataSnapshot) View(android.view.View) AdapterView(android.widget.AdapterView) ListView(android.widget.ListView) DatabaseError(com.google.firebase.database.DatabaseError) AdapterView(android.widget.AdapterView) ValueEventListener(com.google.firebase.database.ValueEventListener) Toolbar(android.support.v7.widget.Toolbar)

Aggregations

DatabaseError (com.google.firebase.database.DatabaseError)61 DataSnapshot (com.google.firebase.database.DataSnapshot)59 ValueEventListener (com.google.firebase.database.ValueEventListener)44 DatabaseReference (com.google.firebase.database.DatabaseReference)22 View (android.view.View)21 Intent (android.content.Intent)15 LinearLayoutManager (android.support.v7.widget.LinearLayoutManager)13 RecyclerView (android.support.v7.widget.RecyclerView)13 User (com.polito.mad17.madmax.entities.User)12 MutableData (com.google.firebase.database.MutableData)11 Transaction (com.google.firebase.database.Transaction)11 Bundle (android.os.Bundle)10 TextView (android.widget.TextView)9 ChatMessageHelper (ingage.ingage20.helpers.ChatMessageHelper)8 ImageView (android.widget.ImageView)6 SimpleDateFormat (java.text.SimpleDateFormat)6 HashMap (java.util.HashMap)6 Map (java.util.Map)6 ChildEventListener (com.google.firebase.database.ChildEventListener)5 Event (com.polito.mad17.madmax.entities.Event)5