use of com.google.firebase.database.DatabaseError 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;
}
use of com.google.firebase.database.DatabaseError 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.DatabaseError in project MadMax by deviz92.
the class ExpenseEdit method updateExpense.
private boolean updateExpense(final Expense expense) {
Log.i(TAG, "update expense");
if (!validateForm()) {
Log.i(TAG, "submitted form is not valid");
Toast.makeText(this, getString(R.string.invalid_form), Toast.LENGTH_SHORT).show();
return false;
}
String newDescription = expenseDescriptionView.getText().toString();
String newCurrency = expenseCurrencyView.getSelectedItem().toString();
if (!newDescription.isEmpty() && (expense.getDescription() == null || !expense.getDescription().equals(newDescription))) {
expense.setDescription(newDescription);
databaseReference.child(expense_type).child(expense.getID()).child("description").setValue(expense.getDescription());
}
if (EXPENSE_TYPE.equals(Event.EventType.PENDING_EXPENSE_EDIT)) {
Double newAmount = Double.valueOf(expenseAmountView.getText().toString());
if (!newAmount.isNaN() && (expense.getAmount() == null || !expense.getAmount().equals(newAmount))) {
expense.setAmount(newAmount);
databaseReference.child(expense_type).child(expense.getID()).child("amount").setValue(expense.getAmount());
}
}
if (!newCurrency.isEmpty() && (expense.getCurrency() == null || !expense.getCurrency().equals(newCurrency))) {
expense.setCurrency(newCurrency);
databaseReference.child(expense_type).child(expense.getID()).child("currency").setValue(expense.getCurrency());
}
if (IMAGE_CHANGED) {
// for saving image
StorageReference uExpenseImageImageFilenameRef = storageReference.child(expense_type).child(expense.getID()).child(expense.getID() + "_expensePhoto.jpg");
// Get the data from an ImageView as bytes
expenseImageView.setDrawingCacheEnabled(true);
expenseImageView.buildDrawingCache();
Bitmap bitmap = expenseImageView.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
UploadTask uploadTask = uExpenseImageImageFilenameRef.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
// todo Handle unsuccessful uploads
Log.e(TAG, "image upload failed");
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
expense.setExpensePhoto(taskSnapshot.getMetadata().getDownloadUrl().toString());
databaseReference.child(expense_type).child(expense.getID()).child("expensePhoto").setValue(expense.getExpensePhoto());
}
});
}
if (BILL_CHANGED) {
// for saving image
StorageReference uExpenseBillImageFilenameRef = storageReference.child(expense_type).child(expense.getID()).child(expense.getID() + "billPhoto.jpg");
// Get the data from an ImageView as bytes
expenseBillView.setDrawingCacheEnabled(true);
expenseBillView.buildDrawingCache();
Bitmap bitmap = expenseBillView.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
UploadTask uploadTask = uExpenseBillImageFilenameRef.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
// todo Handle unsuccessful uploads
Log.e(TAG, "image upload failed");
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
expense.setBillPhoto(taskSnapshot.getMetadata().getDownloadUrl().toString());
databaseReference.child(expense_type).child(expense.getID()).child("billPhoto").setValue(expense.getExpensePhoto());
}
});
}
// add event for EXPENSE_EDIT / PENDING_EXPENSE_EDIT
databaseReference.child(expense_type).child(expense.getID()).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
User currentUser = MainActivity.getCurrentUser();
Event event = new Event(dataSnapshot.child("groupID").getValue(String.class), EXPENSE_TYPE, 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());
}
});
return true;
}
use of com.google.firebase.database.DatabaseError in project MadMax by deviz92.
the class FriendsFragment method onCreateView.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final String activityName = getActivity().getClass().getSimpleName();
Log.d(TAG, "Sono nella activity: " + activityName);
final View view = inflater.inflate(R.layout.skeleton_list, container, false);
databaseReference = FirebaseDatabase.getInstance().getReference();
friends.clear();
setInterface((OnItemClickInterface) getActivity(), (OnItemLongClickInterface) getActivity());
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);
friendsViewAdapter = new FriendsViewAdapter(this.getContext(), this, this, friends, groupDetail);
recyclerView.setAdapter(friendsViewAdapter);
// Se sono in MainActivity visualizzo lista degli amici
if (activityName.equals("MainActivity")) {
query = databaseReference.child("users").child(MainActivity.getCurrentUID()).child("friends");
} else // Se sono dentro un gruppo, visualizzo lista membri del gruppo
if (activityName.equals("GroupDetailActivity")) {
Bundle b = this.getArguments();
if (b != null) {
groupID = b.getString("groupID");
query = databaseReference.child("groups").child(groupID).child("members");
}
}
Log.d(TAG, "query: " + query);
groupMembersListener = query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(final DataSnapshot externalDataSnapshot) {
// svuoto la map, così se viene eliminato uno user dal db, non viene tenuto nella map che si ricarica da zero
friends.clear();
for (final DataSnapshot friendSnapshot : externalDataSnapshot.getChildren()) {
// getFriend(friendSnapshot.getKey());
if (activityName.equals("MainActivity")) {
Log.d(TAG, "key: " + friendSnapshot.getKey());
Log.d(TAG, "value: " + friendSnapshot.getValue());
if (!listenedFriends)
listenedFriends = true;
// Log.d(TAG, friendSnapshot.child("deleted").getValue() + " ");
deleted = friendSnapshot.child("deleted").getValue(Boolean.class);
if (deleted == null) {
deleted = true;
}
if (deleted)
Log.d(TAG, friendSnapshot.getKey() + " is cancelled");
} else if (activityName.equals("GroupDetailActivity")) {
deleted = friendSnapshot.child("deleted").getValue(Boolean.class);
if (deleted == null) {
deleted = true;
}
// Se sono negli amici "generali" e non nei membri di un gruppo, non c'è il campo deleted, quindi sarà null
if (!listenedGroups.contains(groupID))
listenedGroups.add(groupID);
}
if (!deleted) {
final String id = friendSnapshot.getKey();
databaseReference.child("users").child(id).addValueEventListener(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 profileImage = dataSnapshot.child("image").getValue(String.class);
if (activityName.equals("MainActivity")) {
User u = new User();
u.setID(friendSnapshot.getKey());
u.setName(name);
u.setSurname(surname);
u.setProfileImage(profileImage);
if (!deleted)
friends.put(id, u);
else
friends.remove(id);
friendsViewAdapter.update(friends);
friendsViewAdapter.notifyDataSetChanged();
} else if (activityName.equals("GroupDetailActivity")) {
getUserAndGroupBalance(id, name, surname, profileImage, groupID);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
friendsViewAdapter.update(friends);
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, databaseError.getMessage());
}
});
Log.d(TAG, "dopo setAdapter");
return view;
}
use of com.google.firebase.database.DatabaseError in project MadMax by deviz92.
the class User method joinGroup.
public void joinGroup(String groupID, String inviterID) {
final DatabaseReference databaseReference = FirebaseUtils.getDatabaseReference();
final String currentUID = this.getID();
// Aggiungo gruppo alla lista gruppi dello user
databaseReference.child("users").child(currentUID).child("groups").push();
databaseReference.child("users").child(currentUID).child("groups").child(groupID).setValue("true");
// Aggiungo user (con sottocampi admin e timestamp) alla lista membri del gruppo
databaseReference.child("groups").child(groupID).child("members").push();
databaseReference.child("groups").child(groupID).child("members").child(currentUID).push();
databaseReference.child("groups").child(groupID).child("members").child(currentUID).child("admin").setValue(false);
databaseReference.child("groups").child(groupID).child("members").child(currentUID).push();
String timestamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new java.util.Date());
databaseReference.child("groups").child(groupID).child("members").child(currentUID).child("timestamp").setValue(timestamp);
// aggiunto da riky
databaseReference.child("groups").child(groupID).child("members").child(currentUID).push();
databaseReference.child("groups").child(groupID).child("members").child(currentUID).child("deleted").setValue(false);
// aggiungo l'invitante agli amici se non lo è già
if (!userFriends.containsKey(inviterID)) {
// todo aggiungere l'invitato tra gli amici dell'invitante
addFriend(inviterID);
}
// Incremento il numero di partecipanti
databaseReference.child("groups").child(groupID).child("numberMembers").runTransaction(new Transaction.Handler() {
@Override
public Transaction.Result doTransaction(MutableData mutableData) {
Integer numberMembers = mutableData.getValue(Integer.class);
if (numberMembers == null) {
return Transaction.success(mutableData);
}
// Set value and report transaction success
mutableData.setValue(numberMembers + 1);
return Transaction.success(mutableData);
}
@Override
public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
// Transaction completed
Log.d(TAG, "postTransaction:onComplete:" + databaseError);
}
});
}
Aggregations