use of com.google.firebase.database.ValueEventListener in project NPSmiles by bmcglynn1.
the class NewsFragment method onCreateView.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View viewer = inflater.inflate(R.layout.activity_news_feed, container, false);
View popupLayout = inflater.inflate(R.layout.popup_layout_logged_in, null);
final ListView list = (ListView) viewer.findViewById(R.id.list);
final ArrayList<NewsMessage> newsList = new ArrayList<>();
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("Reference");
mAuth = FirebaseAuth.getInstance();
if (mAuth.getCurrentUser() != null) {
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
PopupMenu popup = new PopupMenu(parent.getContext(), view);
popup.getMenuInflater().inflate(R.menu.popup_menu, popup.getMenu());
final TextView title = (TextView) view.findViewById(R.id.title);
final TextView message = (TextView) view.findViewById(R.id.information);
if (mAuth.getCurrentUser() != null) {
popup.show();
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch(item.getItemId()) {
case R.id.EditMenu:
// refresh view if needed
break;
case R.id.DeleteMenu:
// delete from firebase
// refresh view
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("Reference");
Query titleQuery = myRef.child(title.getText().toString());
titleQuery.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot titleSnapshot : dataSnapshot.getChildren()) {
dataSnapshot.getRef().removeValue();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
break;
}
return true;
}
});
}
}
});
}
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
newsList.clear();
for (DataSnapshot newsItem : dataSnapshot.getChildren()) {
NewsMessage newsMessage = new NewsMessage();
for (DataSnapshot item : newsItem.getChildren()) {
if (item.getKey().equals("title")) {
newsMessage.setTitle((String) item.getValue());
} else if (item.getKey().equals("message")) {
newsMessage.setMessage((String) item.getValue());
} else {
newsMessage.setDate((String) item.getValue());
}
}
newsList.add(newsMessage);
}
Collections.sort(newsList);
CustomAdapter adapter = new CustomAdapter(context, newsList);
list.setAdapter(adapter);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
return viewer;
}
use of com.google.firebase.database.ValueEventListener 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) {
FirebaseUtils.getInstance().removeFromFriends(currentUID, itemID);
Toast.makeText(MainActivity.this, getString(R.string.friend_removed), 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(), getString(R.string.credit_group), Toast.LENGTH_LONG);
toast.show();
} else if (returnValue == 1) {
makeText(getApplicationContext(), getString(R.string.debit_group), Toast.LENGTH_LONG).show();
} else if (returnValue == 2) {
makeText(getApplicationContext(), getString(R.string.leaving), Toast.LENGTH_LONG).show();
} else if (returnValue == null) {
makeText(getApplicationContext(), getString(R.string.balance_not_available), 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, getString(R.string.not_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.ValueEventListener 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;
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.ValueEventListener 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;
}
use of com.google.firebase.database.ValueEventListener 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;
}
Aggregations