use of com.google.firebase.database.ValueEventListener 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) {
}
});
}
use of com.google.firebase.database.ValueEventListener 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) {
}
});
}
use of com.google.firebase.database.ValueEventListener 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);
}
});
}
use of com.google.firebase.database.ValueEventListener in project MadMax by deviz92.
the class User method addFriend.
public void addFriend(final String friendID) {
final DatabaseReference databaseReference = FirebaseUtils.getDatabaseReference();
final DatabaseReference usersRef = databaseReference.child("users");
final DatabaseReference groupsRef = databaseReference.child("groups");
final String currentUID = this.getID();
// getting friend data from db
DatabaseReference friendRef = usersRef.child(friendID);
User friend = new User(friendID, friendRef.child("username").toString(), friendRef.child("name").toString(), friendRef.child("surname").toString(), friendRef.child("email").toString(), friendRef.child("profileImage").toString());
// Add friendID to friend list of currentUID
// add friend to current user local HashMap
this.userFriends.put(friendID, friend);
usersRef.child(currentUID).child("friends").push();
usersRef.child(currentUID).child("friends").child(friendID).child("deleted").setValue(false);
// Add currentUID to friend list of friendID
usersRef.child(friendID).child("friends").push();
usersRef.child(friendID).child("friends").child(currentUID).child("deleted").setValue(false);
// Read groups currentUID belongs to
Query query = databaseReference.child("users").child(currentUID).child("groups");
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
final ArrayList<String> u1Groups = new ArrayList<String>();
for (DataSnapshot groupSnapshot : dataSnapshot.getChildren()) {
Log.d(TAG, groupSnapshot.getKey() + " : " + groupSnapshot.getValue());
if (groupSnapshot.getValue(Boolean.class))
u1Groups.add(groupSnapshot.getKey());
}
Query query = databaseReference.child("users").child(friendID).child("groups");
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
ArrayList<String> sharedGroups = new ArrayList<String>();
for (DataSnapshot groupSnapshot : dataSnapshot.getChildren()) {
if (u1Groups.contains(groupSnapshot.getKey()) && groupSnapshot.getValue(Boolean.class))
sharedGroups.add(groupSnapshot.getKey());
}
final HashMap<String, Group> groups = new HashMap<>();
// ora in sharedGroups ci sono solo i gruppi di cui fanno parte entrambi gli utenti
for (String groupID : sharedGroups) {
// getting group data from db
DatabaseReference groupRef = groupsRef.child(groupID);
Group group = new Group(groupID, groupRef.child("name").toString(), groupRef.child("image").toString(), groupRef.child("description").toString(), Integer.parseInt(groupRef.child("numberMembers").toString()));
groups.put(friendID, group);
usersRef.child(currentUID).child("friends").child(friendID).child(groupID).setValue(true);
usersRef.child(friendID).child("friends").child(currentUID).child(groupID).setValue(true);
}
// add shared groups to local sharedGroupPerFriend HashMap
sharedGroupPerFriend.put(friendID, groups);
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.w("addFriendFirebase", databaseError.getMessage());
}
});
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.w("addFriendFirebase", databaseError.getMessage());
}
});
}
use of com.google.firebase.database.ValueEventListener in project MadMax by deviz92.
the class PendingExpensesFragment method onCreateView.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.d(TAG, "onCreateView");
setInterface((OnItemClickInterface) getActivity(), (OnItemLongClickInterface) getActivity());
View view = inflater.inflate(R.layout.skeleton_list, 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) view.findViewById(R.id.rv_skeleton);
layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(layoutManager);
recyclerView.addItemDecoration(divider);
pendingExpenseViewAdapter = new PendingExpenseViewAdapter(this.getContext(), this, this, pendingExpensesMap);
recyclerView.setAdapter(pendingExpenseViewAdapter);
// Ascolto le pending expenses dello user
databaseReference.child("users").child(MainActivity.getCurrentUID()).child("proposedExpenses").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Per ogni pending expense dello user
for (DataSnapshot pendingExpenseSnap : dataSnapshot.getChildren()) {
// Se la pending expense non è stata eliminata (NELLO USER)
if (pendingExpenseSnap.getValue(Boolean.class)) {
FirebaseUtils.getInstance().getPendingExpense(pendingExpenseSnap.getKey(), pendingExpensesMap, pendingExpenseViewAdapter);
pendingExpenseViewAdapter.update(pendingExpensesMap);
pendingExpenseViewAdapter.notifyDataSetChanged();
} else {
// tolgo la spesa da quelle che verranno stampate, così la vedo sparire realtime
pendingExpensesMap.remove(pendingExpenseSnap.getKey());
pendingExpenseViewAdapter.update(pendingExpensesMap);
pendingExpenseViewAdapter.notifyDataSetChanged();
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
return view;
}
Aggregations