Search in sources :

Example 66 with DatabaseReference

use of com.google.firebase.database.DatabaseReference in project quickstart-android by firebase.

the class PostListFragment method onActivityCreated.

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    // Set up Layout Manager, reverse layout
    mManager = new LinearLayoutManager(getActivity());
    mManager.setReverseLayout(true);
    mManager.setStackFromEnd(true);
    mRecycler.setLayoutManager(mManager);
    // Set up FirebaseRecyclerAdapter with the Query
    Query postsQuery = getQuery(mDatabase);
    FirebaseRecyclerOptions options = new FirebaseRecyclerOptions.Builder<Post>().setQuery(postsQuery, Post.class).build();
    mAdapter = new FirebaseRecyclerAdapter<Post, PostViewHolder>(options) {

        @Override
        public PostViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
            LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
            return new PostViewHolder(inflater.inflate(R.layout.item_post, viewGroup, false));
        }

        @Override
        protected void onBindViewHolder(PostViewHolder viewHolder, int position, final Post model) {
            final DatabaseReference postRef = getRef(position);
            // Set click listener for the whole post view
            final String postKey = postRef.getKey();
            viewHolder.itemView.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // Launch PostDetailFragment
                    NavController navController = Navigation.findNavController(requireActivity(), R.id.nav_host_fragment);
                    Bundle args = new Bundle();
                    args.putString(PostDetailFragment.EXTRA_POST_KEY, postKey);
                    navController.navigate(R.id.action_MainFragment_to_PostDetailFragment, args);
                }
            });
            // Determine if the current user has liked this post and set UI accordingly
            if (model.stars.containsKey(getUid())) {
                viewHolder.starView.setImageResource(R.drawable.ic_toggle_star_24);
            } else {
                viewHolder.starView.setImageResource(R.drawable.ic_toggle_star_outline_24);
            }
            // Bind Post to ViewHolder, setting OnClickListener for the star button
            viewHolder.bindToPost(model, new View.OnClickListener() {

                @Override
                public void onClick(View starView) {
                    // Need to write to both places the post is stored
                    DatabaseReference globalPostRef = mDatabase.child("posts").child(postRef.getKey());
                    DatabaseReference userPostRef = mDatabase.child("user-posts").child(model.uid).child(postRef.getKey());
                    // Run two transactions
                    onStarClicked(globalPostRef);
                    onStarClicked(userPostRef);
                }
            });
        }
    };
    mRecycler.setAdapter(mAdapter);
}
Also used : FirebaseRecyclerOptions(com.firebase.ui.database.FirebaseRecyclerOptions) PostViewHolder(com.google.firebase.quickstart.database.java.viewholder.PostViewHolder) Query(com.google.firebase.database.Query) DatabaseReference(com.google.firebase.database.DatabaseReference) Post(com.google.firebase.quickstart.database.java.models.Post) ViewGroup(android.view.ViewGroup) Bundle(android.os.Bundle) NavController(androidx.navigation.NavController) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) LayoutInflater(android.view.LayoutInflater)

Example 67 with DatabaseReference

use of com.google.firebase.database.DatabaseReference in project FirebaseUI-Android by firebase.

the class FirebaseArrayOfObjectsTest method testCacheInvalidates.

@Test
public void testCacheInvalidates() throws Exception {
    final DatabaseReference pushRef = mRef.push();
    // Set initial value to "5"
    runAndWaitUntil(mArray, () -> pushRef.setValue(new Bean(5), 100), () -> mArray.get(3).getNumber() == 5);
    // Change the value to "6" and ensure that the change is propagated
    runAndWaitUntil(mArray, () -> pushRef.setValue(new Bean(6), 100), () -> mArray.get(3).getNumber() == 6);
}
Also used : DatabaseReference(com.google.firebase.database.DatabaseReference) Test(org.junit.Test)

Example 68 with DatabaseReference

use of com.google.firebase.database.DatabaseReference in project MadMax by deviz92.

the class ProposedExpenseCommentsFragment method onCreateView.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    RecyclerView recyclerView;
    RecyclerView.LayoutManager layoutManager;
    String expenseID;
    View view = inflater.inflate(R.layout.skeleton_list, container, false);
    Bundle fragmentArguments = getArguments();
    expenseID = fragmentArguments.getString("expenseID");
    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) view.findViewById(R.id.rv_skeleton);
    layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.addItemDecoration(divider);
    expenseCommentsViewAdapter = new ExpenseCommentsViewAdapter(this.getContext(), this, commentsMap, getFragmentManager());
    recyclerView.setAdapter(expenseCommentsViewAdapter);
    DatabaseReference expenseRef = databaseReference.child("proposedExpenses");
    expenseRef.child(expenseID).child("comments").addValueEventListener(new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot commentSnapshot) {
            for (DataSnapshot comment : commentSnapshot.getChildren()) {
                FirebaseUtils.getInstance().getComment(comment.getKey(), commentsMap, expenseCommentsViewAdapter);
                Log.d(TAG, comment.getKey());
            }
            expenseCommentsViewAdapter.update(commentsMap);
        }

        @Override
        public void onCancelled(DatabaseError error) {
            // Failed to read value
            Log.w(TAG, "Failed to read value.", error.toException());
        }
    });
    return view;
}
Also used : DatabaseReference(com.google.firebase.database.DatabaseReference) Bundle(android.os.Bundle) LinearLayoutManager(android.support.v7.widget.LinearLayoutManager) DataSnapshot(com.google.firebase.database.DataSnapshot) RecyclerView(android.support.v7.widget.RecyclerView) View(android.view.View) DatabaseError(com.google.firebase.database.DatabaseError) RecyclerView(android.support.v7.widget.RecyclerView) ValueEventListener(com.google.firebase.database.ValueEventListener)

Example 69 with DatabaseReference

use of com.google.firebase.database.DatabaseReference in project MadMax by deviz92.

the class NewExpenseActivity method onOptionsItemSelected.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    DatabaseReference groupRef;
    int itemThatWasClickedId = item.getItemId();
    if (itemThatWasClickedId == R.id.action_save) {
        if (!validateForm())
            return true;
        // display message if text field is empty
        Toast.makeText(getBaseContext(), getString(R.string.expense_saved), Toast.LENGTH_SHORT).show();
        final Expense newExpense = new Expense();
        newExpense.setDescription(description.getText().toString());
        newExpense.setAmount(Double.valueOf(amount.getText().toString()));
        newExpense.setCurrency(currency.getSelectedItem().toString());
        newExpense.setGroupID(groupID);
        newExpense.setCreatorID(userID);
        newExpense.setEquallyDivided(true);
        newExpense.setDeleted(false);
        Log.d(TAG, "Before first access to firebase");
        if (equalSplit)
            addEqualExpense(newExpense, groupID);
        else
            addUnequalExpense(newExpense, groupID, members);
    }
    this.finish();
    return super.onOptionsItemSelected(item);
}
Also used : DatabaseReference(com.google.firebase.database.DatabaseReference) Expense(com.polito.mad17.madmax.entities.Expense)

Example 70 with DatabaseReference

use of com.google.firebase.database.DatabaseReference 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());
        }
    });
}
Also used : User(com.polito.mad17.madmax.entities.User) DatabaseReference(com.google.firebase.database.DatabaseReference) Intent(android.content.Intent) MainActivity(com.polito.mad17.madmax.activities.MainActivity) DataSnapshot(com.google.firebase.database.DataSnapshot) DatabaseError(com.google.firebase.database.DatabaseError) Event(com.polito.mad17.madmax.entities.Event) MotionEvent(android.view.MotionEvent) ValueEventListener(com.google.firebase.database.ValueEventListener) SimpleDateFormat(java.text.SimpleDateFormat)

Aggregations

DatabaseReference (com.google.firebase.database.DatabaseReference)157 DatabaseError (com.google.firebase.database.DatabaseError)95 DataSnapshot (com.google.firebase.database.DataSnapshot)87 ValueEventListener (com.google.firebase.database.ValueEventListener)61 FirebaseDatabase (com.google.firebase.database.FirebaseDatabase)50 HashMap (java.util.HashMap)24 View (android.view.View)18 MutableData (com.google.firebase.database.MutableData)17 Transaction (com.google.firebase.database.Transaction)17 Intent (android.content.Intent)16 FirebaseUser (com.google.firebase.auth.FirebaseUser)13 ArrayList (java.util.ArrayList)12 TextView (android.widget.TextView)11 Query (com.google.firebase.database.Query)11 Map (java.util.Map)11 ProgressDialog (android.app.ProgressDialog)10 LinearLayoutManager (android.support.v7.widget.LinearLayoutManager)10 ChildEventListener (com.google.firebase.database.ChildEventListener)9 SharedPreferences (android.content.SharedPreferences)8 ChatMessageHelper (ingage.ingage20.helpers.ChatMessageHelper)8