use of com.google.firebase.database.DataSnapshot 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")) {
// Inflate the layout for this fragment
mainView = inflater.inflate(R.layout.shared_groups_list, container, false);
RecyclerView.ItemDecoration divider = new InsetDivider.Builder(getContext()).orientation(InsetDivider.VERTICAL_LIST).dividerHeight(getResources().getDimensionPixelSize(R.dimen.divider_height)).color(getResources().getColor(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;
}
use of com.google.firebase.database.DataSnapshot in project MadMax by deviz92.
the class MainActivity method itemLongClicked.
//Apro popup menu quando ho tenuto premuto un friend o gruppo per 1 secondo
@Override
public void itemLongClicked(String fragmentName, final String itemID, final View v) {
Log.i(TAG, "fragmentName " + fragmentName + " itemID " + itemID);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Bundle bundle = new Bundle();
Intent intent = null;
switch(fragmentName) {
case "FriendsFragment":
PopupMenu popup = new PopupMenu(MainActivity.this, v, Gravity.RIGHT);
popup.getMenuInflater().inflate(R.menu.longclick_popup_menu, popup.getMenu());
one = popup.getMenu().findItem(R.id.one);
one.setTitle("Remove Friend");
popup.getMenu().findItem(R.id.two).setVisible(false);
popup.getMenu().findItem(R.id.three).setVisible(false);
//registering popup with OnMenuItemClickListener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(MainActivity.this, "You Clicked : " + item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
}
});
//showing popup menu
popup.show();
break;
case "GroupsFragment":
popup = new PopupMenu(MainActivity.this, v, Gravity.RIGHT);
popup.getMenuInflater().inflate(R.menu.longclick_popup_menu, popup.getMenu());
one = popup.getMenu().findItem(R.id.one);
one.setTitle("Leave this Group");
two = popup.getMenu().findItem(R.id.two);
two.setTitle("Remove this Group");
popup.getMenu().findItem(R.id.three).setVisible(false);
//registering popup with OnMenuItemClickListener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
switch((String) item.getTitle()) {
case "Leave this Group":
Integer returnValue = FirebaseUtils.getInstance().leaveGroupFirebase(currentUID, itemID);
if (returnValue == 0) {
Toast toast = Toast.makeText(getApplicationContext(), "Hai un credito verso questo gruppo.\nAbbandonare comunque?", Toast.LENGTH_LONG);
toast.show();
} else if (returnValue == 1) {
makeText(getApplicationContext(), "Hai un debito verso questo gruppo.\nSalda il debito per poter abbandonare.", Toast.LENGTH_LONG).show();
} else if (returnValue == 2) {
makeText(getApplicationContext(), "Nessuno debito, abbandono in corso.", Toast.LENGTH_LONG).show();
} else if (returnValue == null) {
makeText(getApplicationContext(), "Bilancio del gruppo: non disponibile adesso.\nRiprovare.", Toast.LENGTH_LONG).show();
}
break;
case "Remove this Group":
FirebaseUtils.getInstance().removeGroupFirebase(currentUID, itemID, getApplicationContext());
break;
}
return true;
}
});
//showing popup menu
popup.show();
break;
case "PendingExpensesFragment":
popup = new PopupMenu(MainActivity.this, v, Gravity.RIGHT);
popup.getMenuInflater().inflate(R.menu.longclick_popup_menu, popup.getMenu());
one = popup.getMenu().findItem(R.id.one);
one.setTitle("Remove Pending");
popup.getMenu().findItem(R.id.two).setVisible(false);
popup.getMenu().findItem(R.id.three).setVisible(false);
//registering popup with OnMenuItemClickListener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
databaseReference.child("proposedExpenses").child(itemID).child("creatorID").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (MainActivity.getCurrentUser().getID().matches(dataSnapshot.getValue(String.class))) {
FirebaseUtils.getInstance().removePendingExpenseFirebase(itemID, getApplicationContext());
// add event for PENDING_EXPENSE_REMOVE
databaseReference.child("proposedExpenses").child(itemID).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
User currentUser = MainActivity.getCurrentUser();
Event event = new Event(dataSnapshot.child("groupID").getValue(String.class), Event.EventType.PENDING_EXPENSE_REMOVE, 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());
}
});
} else
Toast.makeText(MainActivity.this, "You are not the proposal creator", Toast.LENGTH_SHORT).show();
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
return true;
}
});
//showing popup menu
popup.show();
break;
}
}
use of com.google.firebase.database.DataSnapshot in project MadMax by deviz92.
the class ExpensesFragment method onCreateView.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
String groupID;
setInterface((OnItemClickInterface) getActivity(), (OnItemLongClickInterface) getActivity());
View view = inflater.inflate(R.layout.skeleton_list, container, false);
Bundle bundle = getArguments();
groupID = bundle.getString("groupID");
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) view.findViewById(R.id.rv_skeleton);
layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(layoutManager);
recyclerView.addItemDecoration(divider);
expensesViewAdapter = new ExpensesViewAdapter(this.getContext(), this, this, expensesMap);
recyclerView.setAdapter(expensesViewAdapter);
groupRef = databaseReference.child("groups");
Log.d(TAG, groupID);
// retrieving group details for current group
groupRef.child(groupID).child("expenses").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot expensesSnapshot) {
for (DataSnapshot expense : expensesSnapshot.getChildren()) {
FirebaseUtils.getInstance().getExpense(expense.getKey(), expensesMap, expensesViewAdapter);
Log.d(TAG, expense.getKey());
}
expensesViewAdapter.update(expensesMap);
}
@Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
return view;
}
use of com.google.firebase.database.DataSnapshot 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.getCurrentUser().getID()) && !groupDataSnapshot.child("members").child(MainActivity.getCurrentUser().getID()).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);
Log.d(TAG, "Fraction: " + Double.parseDouble(String.valueOf(dataSnapshot.child("participants").child(userID).child("fraction").getValue())));
Double dueImport = Double.parseDouble(String.valueOf(dataSnapshot.child("participants").child(userID).child("fraction").getValue())) * dataSnapshot.child("amount").getValue(Double.class);
Double balance = alreadyPaid - dueImport;
String currency = dataSnapshot.child("currency").getValue(String.class);
//se user per quella spesa ha già pagato più soldi della sua quota, il balance è positivo
//current balance for that currency
Double temp = totBalances.get(currency);
//update balance for that currency
if (temp != null) {
totBalances.put(currency, temp + balance);
Log.d(TAG, "Actual debt for " + groupName + ": " + totBalances.get(currency) + " " + currency);
} else {
totBalances.put(currency, balance);
Log.d(TAG, "Actual debt for " + groupName + ": " + totBalances.get(currency) + " " + currency);
}
//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.getCurrentUser().getID()) && !groupDataSnapshot.child("members").child(MainActivity.getCurrentUser().getID()).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) {
}
});
}
use of com.google.firebase.database.DataSnapshot 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) {
}
});
}
Aggregations