use of com.google.firebase.database.ValueEventListener in project MadMax by deviz92.
the class ExpenseEdit method onCreate.
@Override
@TargetApi(23)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_expense);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
expenseImageView = (ImageView) this.findViewById(R.id.expense_image);
expenseBillView = (ImageView) this.findViewById(R.id.expense_bill);
expenseDescriptionView = (EditText) this.findViewById(R.id.expense_description);
expenseAmountView = (EditText) this.findViewById(R.id.expense_amount);
expenseCurrencyView = (Spinner) this.findViewById(R.id.expense_currency);
saveButton = (Button) this.findViewById(R.id.btn_save);
// creating spinner for currencies
final ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.currencies, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
expenseCurrencyView.setAdapter(adapter);
Intent intent = getIntent();
String expenseID = intent.getStringExtra("expenseID");
if (intent.getStringExtra("EXPENSE_TYPE").equals("EXPENSE_EDIT")) {
EXPENSE_TYPE = Event.EventType.EXPENSE_EDIT;
expense_type = "expenses";
} else {
EXPENSE_TYPE = Event.EventType.PENDING_EXPENSE_EDIT;
expense_type = "proposedExpenses";
}
databaseReference.child(expense_type).child(expenseID).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
expense = new Expense();
expense.setID(dataSnapshot.getKey());
expense.setDescription(dataSnapshot.child("description").getValue(String.class));
expense.setCurrency(dataSnapshot.child("currency").getValue(String.class));
expense.setExpensePhoto(dataSnapshot.child("expensePhoto").getValue(String.class));
expense.setBillPhoto(dataSnapshot.child("billPhoto").getValue(String.class));
final String groupID = dataSnapshot.child("groupID").getValue(String.class);
expenseDescriptionView.setText(expense.getDescription());
if (EXPENSE_TYPE.equals(Event.EventType.PENDING_EXPENSE_EDIT)) {
expense.setAmount(dataSnapshot.child("amount").getValue(Double.class));
expenseAmountView.setText(String.valueOf(expense.getAmount()));
}
// set the defaultCurrency value for the spinner based on the user preferences
int spinnerPosition = adapter.getPosition(expense.getCurrency());
expenseCurrencyView.setSelection(spinnerPosition);
// progressDialog = new ProgressDialog(ProfileEdit.this);
// loading expense photo (if present)
String expenseImage = expense.getExpensePhoto();
if (expenseImage != null && !expenseImage.equals("")) {
// Loading image
Glide.with(getApplicationContext()).load(expenseImage).centerCrop().diskCacheStrategy(DiskCacheStrategy.ALL).into(expenseImageView);
} else {
// Loading image
expenseImageView.setImageResource(R.drawable.add_photo);
/* Glide.with(getApplicationContext()).load(R.drawable.add_photo)
.centerCrop()
//.bitmapTransform(new CropCircleTransformation(this))
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(expenseImageView);*/
}
expenseImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i(TAG, "expense image clicked");
if (MainActivity.shouldAskPermission()) {
String[] perms = { "android.permission.READ_EXTERNAL_STORAGE" };
int permsRequestCode = 200;
requestPermissions(perms, permsRequestCode);
}
// allow to the user the choose image
Intent intent = new Intent();
// Show only images, no videos or anything else
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
// Always show the chooser (if there are multiple options available)
startActivityForResult(Intent.createChooser(intent, "Select picture"), PICK_IMAGE_REQUEST);
// now see onActivityResult
}
});
// loading expense bill (if present)
String expenseBill = expense.getBillPhoto();
if (expenseBill != null && !expenseBill.equals("")) {
// Loading image
Glide.with(getApplicationContext()).load(expenseBill).centerCrop().diskCacheStrategy(DiskCacheStrategy.ALL).into(expenseBillView);
} else {
// Loading image
expenseImageView.setImageResource(R.drawable.add_photo);
/*Glide.with(getApplicationContext()).load(R.drawable.add_photo)
.centerCrop()
//.bitmapTransform(new CropCircleTransformation(this))
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(expenseBillView);*/
}
expenseBillView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i(TAG, "expense bill clicked");
if (MainActivity.shouldAskPermission()) {
String[] perms = { "android.permission.READ_EXTERNAL_STORAGE" };
int permsRequestCode = 200;
requestPermissions(perms, permsRequestCode);
}
// allow to the user the choose image
Intent intent = new Intent();
// Show only images, no videos or anything else
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
// Always show the chooser (if there are multiple options available)
startActivityForResult(Intent.createChooser(intent, "Select picture"), PICK_BILL_REQUEST);
// now see onActivityResult
}
});
saveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i(TAG, "save clicked");
if (updateExpense(expense)) {
Toast.makeText(ExpenseEdit.this, getString(R.string.saved), Toast.LENGTH_SHORT).show();
Intent intent;
if (EXPENSE_TYPE.equals(Event.EventType.EXPENSE_EDIT)) {
intent = new Intent(getApplicationContext(), ExpenseDetailActivity.class);
intent.putExtra("groupID", expense.getGroupID());
intent.putExtra("expenseID", expense.getID());
intent.putExtra("userID", MainActivity.getCurrentUser().getID());
} else {
intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("currentFragment", 2);
}
startActivity(intent);
finish();
}
}
});
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, databaseError.getMessage());
}
});
}
use of com.google.firebase.database.ValueEventListener in project MadMax by deviz92.
the class NewExpenseActivity method addEqualExpense.
void addEqualExpense(final Expense newExpense, final String groupID) {
DatabaseReference groupRef = databaseReference.child("groups");
groupRef.child(groupID).child("members").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot membersSnapshot) {
int participantsCount = 0;
// Attenzione! Non contare i membri eliminati tra i partecipanti alla spesa
for (DataSnapshot memberSnap : membersSnapshot.getChildren()) {
if (!memberSnap.child("deleted").getValue(Boolean.class)) {
participantsCount++;
}
}
Double amountPerMember = 1 / (double) participantsCount;
for (DataSnapshot member : membersSnapshot.getChildren()) {
// Aggiungo alla spesa solo i membri non eliminati dal gruppo
if (!member.child("deleted").getValue(Boolean.class)) {
newExpense.getParticipants().put(member.getKey(), amountPerMember);
}
}
String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new java.util.Date());
newExpense.setTimestamp(timeStamp);
if (!IMAGE_CHANGED)
expensePhoto = null;
if (!BILL_CHANGED)
billPhoto = null;
// Aggiungo una pending expense
if (callingActivity.equals("ChooseGroupActivity")) {
newExpense.setGroupName(groupName);
if (groupImage != null)
newExpense.setGroupImage(groupImage);
FirebaseUtils.getInstance().addPendingExpenseFirebase(newExpense, expensePhoto, getApplicationContext());
// add event for PENDING_EXPENSE_ADD
User currentUser = MainActivity.getCurrentUser();
Event event = new Event(groupID, Event.EventType.PENDING_EXPENSE_ADD, currentUser.getName() + " " + currentUser.getSurname(), newExpense.getDescription(), newExpense.getAmount());
event.setDate(new SimpleDateFormat("yyyy.MM.dd").format(new java.util.Date()));
event.setTime(new SimpleDateFormat("HH:mm").format(new java.util.Date()));
FirebaseUtils.getInstance().addEvent(event);
Intent myIntent = new Intent(NewExpenseActivity.this, MainActivity.class);
myIntent.putExtra("UID", MainActivity.getCurrentUID());
myIntent.putExtra("currentFragment", 2);
startActivity(myIntent);
} else // Aggiungo una spesa normale
{
FirebaseUtils.getInstance().addExpenseFirebase(newExpense, expensePhoto, billPhoto, getApplicationContext());
// add event for EXPENSE_ADD
User currentUser = MainActivity.getCurrentUser();
Event event = new Event(newExpense.getGroupID(), Event.EventType.EXPENSE_ADD, currentUser.getName() + " " + currentUser.getSurname(), newExpense.getDescription(), newExpense.getAmount());
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 error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
}
use of com.google.firebase.database.ValueEventListener in project MadMax by deviz92.
the class NewExpenseActivity method onCreate.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_expense);
context = NewExpenseActivity.this;
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
String defaultCurrency = sharedPref.getString(SettingsFragment.DEFAULT_CURRENCY, "");
IMAGE_CHANGED = false;
BILL_CHANGED = false;
Intent intent = getIntent();
if (groupID == null)
groupID = intent.getStringExtra("groupID");
userID = intent.getStringExtra("userID");
callingActivity = intent.getStringExtra("callingActivity");
groupName = intent.getStringExtra("groupName");
groupImage = intent.getStringExtra("groupImage");
isNewPending = intent.getBooleanExtra("newPending", false);
description = (EditText) findViewById(R.id.edit_description);
amount = (EditText) findViewById(R.id.edit_amount);
currency = (Spinner) findViewById(R.id.currency);
expensePhoto = (ImageView) findViewById(R.id.img_expense);
billPhoto = (ImageView) findViewById(R.id.img_bill);
billPhotoText = (TextView) findViewById(R.id.tv_bill_expense);
splitButton = (Button) findViewById(R.id.btn_split);
unequalCheckBox = (CheckBox) findViewById(R.id.check_unequal);
splitButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Double value = null;
String text = amount.getText().toString();
if (!text.isEmpty()) {
try {
value = Double.parseDouble(text);
// it means it is double
} catch (Exception e1) {
// this means it is not double
e1.printStackTrace();
}
Intent intent = new Intent(NewExpenseActivity.this, SplitPolicyActivity.class);
intent.putExtra("amount", value);
intent.putExtra("currency", currency.getSelectedItem().toString());
intent.putExtra("participants", members);
intent.putExtra("totalSplit", totalSplit);
intent.putExtra("groupID", groupID);
intent.putExtra("userID", userID);
intent.putExtra("callingActivity", "SplitPolicyActivity");
intent.putExtra("groupName", groupName);
intent.putExtra("groupImage", groupImage);
startActivityForResult(intent, PICK_SPLIT_REQUEST);
} else {
Toast.makeText(getBaseContext(), "Fill amount field", Toast.LENGTH_SHORT).show();
return;
}
}
});
// Add listener to checkbox
addListenerOnUnequalSplit();
if (unequalCheckBox.isChecked()) {
equalSplit = false;
} else {
equalSplit = true;
splitButton.setClickable(false);
}
// creating spinner for currencies
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.currencies, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
currency.setAdapter(adapter);
// set the defaultCurrency value for the spinner based on the user preferences
int spinnerPosition = adapter.getPosition(defaultCurrency);
currency.setSelection(spinnerPosition);
// Add members of this group to a map. It's needed to pass them to SplitPolicyActivity
databaseReference.child("groups").child(groupID).child("members").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot memberSnap : dataSnapshot.getChildren()) {
if (!memberSnap.child("deleted").getValue(Boolean.class)) {
if (!members.containsKey(memberSnap.getKey()))
members.put(memberSnap.getKey(), 0d);
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
expensePhoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i(TAG, "image clicked");
// allow to the user the choose his profile image
Intent intent = new Intent();
// Show only images, no videos or anything else
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
// Always show the chooser (if there are multiple options available)
startActivityForResult(Intent.createChooser(intent, "Select picture"), PICK_EXPENSE_PHOTO_REQUEST);
// now see onActivityResult
}
});
if (isNewPending) {
billPhotoText.setVisibility(View.GONE);
billPhoto.setVisibility(View.GONE);
splitButton.setVisibility(View.GONE);
unequalCheckBox.setVisibility(View.GONE);
} else {
billPhotoText.setVisibility(View.VISIBLE);
billPhoto.setVisibility(View.VISIBLE);
splitButton.setVisibility(View.VISIBLE);
unequalCheckBox.setVisibility(View.VISIBLE);
billPhoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i(TAG, "image clicked");
// allow to the user the choose his profile image
Intent intent = new Intent();
// Show only images, no videos or anything else
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
// Always show the chooser (if there are multiple options available)
startActivityForResult(Intent.createChooser(intent, "Select picture"), PICK_BILL_PHOTO_REQUEST);
// now see onActivityResult
}
});
}
}
use of com.google.firebase.database.ValueEventListener in project MadMax by deviz92.
the class MainActivity method onStart.
@Override
protected void onStart() {
super.onStart();
Log.i(TAG, "onStart");
startingIntent = getIntent();
currentFragment = startingIntent.getIntExtra("currentFragment", 1);
// start declaration of a listener on all the current user data -> attached in onStart()
currentUserListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d(TAG, "onDataChange currentUserref");
if (currentUser == null) {
// makeText(MainActivity.this, "Ricreato user", Toast.LENGTH_SHORT).show(); // todo: di debug, da rimuovere
currentUser = new User();
}
currentUser.setID(currentUID);
currentUser.setName(dataSnapshot.child("name").getValue(String.class));
currentUser.setSurname(dataSnapshot.child("surname").getValue(String.class));
currentUser.setUsername(dataSnapshot.child("username").getValue(String.class));
currentUser.setProfileImage(dataSnapshot.child("image").getValue(String.class));
currentUser.setEmail(dataSnapshot.child("email").getValue(String.class));
currentUser.setPassword(dataSnapshot.child("password").getValue(String.class));
Log.d(TAG, "taken basic data of currentUser " + currentUser.toString());
// get user friends's IDs
if (dataSnapshot.child("friends").hasChildren())
for (DataSnapshot friend : dataSnapshot.child("friends").getChildren()) {
if (!friend.hasChild("deleted") || !friend.child("deleted").getValue(Boolean.class))
currentUser.getUserFriends().put(friend.getKey(), null);
}
// get user groups's IDs
if (dataSnapshot.child("groups").hasChildren())
for (DataSnapshot group : dataSnapshot.child("groups").getChildren()) {
if (group.getValue(Boolean.class))
currentUser.getUserGroups().put(group.getKey(), null);
}
Log.d(TAG, "Taken friends and groups, now creating the adapter");
if (currentFragment != null) {
viewPager.setCurrentItem(currentFragment);
updateFab(currentFragment);
} else {
viewPager.setCurrentItem(1);
updateFab(1);
}
// load nav menu header data for the current user
loadNavHeader();
Log.d(TAG, "logged user name: " + currentUser.getName());
Log.d(TAG, "logged user surname: " + currentUser.getSurname());
Uri data = startingIntent.getData();
if (data != null) {
inviterID = data.getQueryParameter("inviterID");
groupToBeAddedID = data.getQueryParameter("groupToBeAddedID");
} else {
// retrieving data from the intent inviterID & groupToBeAddedID as the group ID where to add the current user
if (startingIntent.hasExtra("inviterID")) {
// to be used to set the current user as friend of the inviter
Log.d(TAG, "there is an invite");
inviterID = startingIntent.getStringExtra("inviterID");
startingIntent.removeExtra("inviterID");
}
if (startingIntent.hasExtra("groupToBeAddedID")) {
groupToBeAddedID = startingIntent.getStringExtra("groupToBeAddedID");
startingIntent.removeExtra("groupToBeAddedID");
}
}
// control if user that requires the friendship is already a friend
if (inviterID != null) {
if (!currentUser.getUserFriends().containsKey(inviterID)) {
FirebaseUtils.getInstance().addFriend(inviterID);
inviterID = null;
makeText(MainActivity.this, getString(R.string.new_friend), Toast.LENGTH_LONG).show();
}
/*else
makeText(MainActivity.this, getString(R.string.already_friends), Toast.LENGTH_LONG).show();*/
}
// control if user is already part of requested group
if (groupToBeAddedID != null) {
if (!currentUser.getUserGroups().containsKey(groupToBeAddedID)) {
// currentUser.joinGroup(groupToBeAddedID); //todo usare questa? non aggiorna il numero dei membri
currentUser.getUserGroups().put(groupToBeAddedID, null);
FirebaseUtils.getInstance().joinGroupFirebase(currentUID, groupToBeAddedID);
groupToBeAddedID = null;
makeText(MainActivity.this, getString(R.string.join_group), Toast.LENGTH_LONG).show();
}
// else
// makeText(MainActivity.this, getString(R.string.already_in_group) + "\""+currentUser.getUserGroups().get(groupToBeAddedID).getName()+"\"", Toast.LENGTH_LONG).show();
}
if (startingIntent.hasExtra("notificationTitle")) {
Intent notificationIntent = null;
switch(startingIntent.getStringExtra("notificationTitle")) {
case "notification_invite":
if (startingIntent.hasExtra("groupID")) {
notificationIntent = new Intent(getApplicationContext(), GroupDetailActivity.class);
notificationIntent.putExtra("groupID", startingIntent.getStringExtra("groupID"));
}
break;
case "notification_expense_added":
if (startingIntent.hasExtra("groupID")) {
notificationIntent = new Intent(getApplicationContext(), ExpenseDetailActivity.class);
notificationIntent.putExtra("groupID", startingIntent.getStringExtra("groupID"));
if (startingIntent.hasExtra("expenseID")) {
notificationIntent.putExtra("expenseID", startingIntent.getStringExtra("expenseID"));
}
}
break;
case "notification_expense_removed":
if (startingIntent.hasExtra("groupID")) {
notificationIntent = new Intent(getApplicationContext(), GroupDetailActivity.class);
notificationIntent.putExtra("groupID", startingIntent.getStringExtra("groupID"));
}
break;
case "notification_proposalExpense_added":
if (startingIntent.hasExtra("expenseID")) {
notificationIntent = new Intent(getApplicationContext(), PendingExpenseDetailActivity.class);
notificationIntent.putExtra("expenseID", startingIntent.getStringExtra("expenseID"));
}
break;
}
if (notificationIntent != null) {
notificationIntent.putExtra("userID", currentUID);
startingIntent.removeExtra("notificationTitle");
startActivityForResult(notificationIntent, REQUEST_NOTIFICATION);
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
// TODO: come gestire?
Log.d(TAG, "getting current user failed");
}
};
// end of listener declaration on all the current user data
authListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
Log.d(TAG, "onAuthStateChanged");
currentFirebaseUser = firebaseAuth.getCurrentUser();
if (currentFirebaseUser != null && currentFirebaseUser.isEmailVerified()) {
// getting reference to the user from db
currentUID = currentFirebaseUser.getUid();
currentUserRef = usersRef.child(currentUID);
// take refreshed toked and save it to use FCM
currentUserRef.child("token").setValue(FirebaseInstanceId.getInstance().getToken());
Log.d(TAG, "device token: " + FirebaseInstanceId.getInstance().getToken());
// attach a listener on all the current user data
currentUserRef.addValueEventListener(currentUserListener);
} else {
Log.d(TAG, "current user is null, so go to login activity");
Intent goToLogin = new Intent(getApplicationContext(), LoginSignUpActivity.class);
// currentUser = null;
startActivity(goToLogin);
auth.removeAuthStateListener(authListener);
finish();
}
}
};
// attach the listener to the FirebaseAuth instance
auth.addAuthStateListener(authListener);
}
use of com.google.firebase.database.ValueEventListener in project MadMax by deviz92.
the class ExpenseDetailFragment method onCreateView.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
Log.i(TAG, "onCreateView");
setInterface((OnItemClickInterface) getActivity());
// Read expenseID from ExpenseDetailPagerAdapter
Bundle b = this.getArguments();
expenseID = b.getString("expenseID");
final 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);
participantsViewAdapter = new ParticipantsViewAdapter(this.getContext(), this, participants);
recyclerView.setAdapter(participantsViewAdapter);
// Ascolto i participants alla spesa
databaseReference.child("expenses").child(expenseID).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Per ogni participant
for (DataSnapshot participantSnap : dataSnapshot.child("participants").getChildren()) {
Double alreadyPaid = participantSnap.child("alreadyPaid").getValue(Double.class);
Double dueImport = alreadyPaid - participantSnap.child("fraction").getValue(Double.class) * dataSnapshot.child("amount").getValue(Double.class);
String currency = dataSnapshot.child("currency").getValue(String.class);
User u = new User();
u.setAlreadyPaid(alreadyPaid);
u.setDueImport(dueImport);
u.setExpenseCurrency(currency);
String participantID = participantSnap.getKey();
FirebaseUtils.getInstance().getParticipantName(participantID, participants, participantsViewAdapter, u);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, databaseError.toException());
}
});
return view;
}
Aggregations