Search in sources :

Example 1 with QuerySnapshot

use of com.google.firebase.firestore.QuerySnapshot in project PhotoBlog-Android-Blog-App by akshayejh.

the class HomeFragment method loadMorePost.

public void loadMorePost() {
    if (firebaseAuth.getCurrentUser() != null) {
        Query nextQuery = firebaseFirestore.collection("Posts").orderBy("timestamp", Query.Direction.DESCENDING).startAfter(lastVisible).limit(3);
        nextQuery.addSnapshotListener(getActivity(), new EventListener<QuerySnapshot>() {

            @Override
            public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
                if (!documentSnapshots.isEmpty()) {
                    lastVisible = documentSnapshots.getDocuments().get(documentSnapshots.size() - 1);
                    for (DocumentChange doc : documentSnapshots.getDocumentChanges()) {
                        if (doc.getType() == DocumentChange.Type.ADDED) {
                            String blogPostId = doc.getDocument().getId();
                            BlogPost blogPost = doc.getDocument().toObject(BlogPost.class).withId(blogPostId);
                            blog_list.add(blogPost);
                            blogRecyclerAdapter.notifyDataSetChanged();
                        }
                    }
                }
            }
        });
    }
}
Also used : Query(com.google.firebase.firestore.Query) FirebaseFirestoreException(com.google.firebase.firestore.FirebaseFirestoreException) DocumentChange(com.google.firebase.firestore.DocumentChange) QuerySnapshot(com.google.firebase.firestore.QuerySnapshot)

Example 2 with QuerySnapshot

use of com.google.firebase.firestore.QuerySnapshot in project PhotoBlog-Android-Blog-App by akshayejh.

the class BlogRecyclerAdapter method onBindViewHolder.

@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
    holder.setIsRecyclable(false);
    final String blogPostId = blog_list.get(position).BlogPostId;
    final String currentUserId = firebaseAuth.getCurrentUser().getUid();
    String desc_data = blog_list.get(position).getDesc();
    holder.setDescText(desc_data);
    String image_url = blog_list.get(position).getImage_url();
    String thumbUri = blog_list.get(position).getImage_thumb();
    holder.setBlogImage(image_url, thumbUri);
    String user_id = blog_list.get(position).getUser_id();
    // User Data will be retrieved here...
    firebaseFirestore.collection("Users").document(user_id).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {

        @Override
        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
            if (task.isSuccessful()) {
                String userName = task.getResult().getString("name");
                String userImage = task.getResult().getString("image");
                holder.setUserData(userName, userImage);
            } else {
            // Firebase Exception
            }
        }
    });
    try {
        long millisecond = blog_list.get(position).getTimestamp().getTime();
        String dateString = DateFormat.format("MM/dd/yyyy", new Date(millisecond)).toString();
        holder.setTime(dateString);
    } catch (Exception e) {
        Toast.makeText(context, "Exception : " + e.getMessage(), Toast.LENGTH_SHORT).show();
    }
    // Get Likes Count
    firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").addSnapshotListener(new EventListener<QuerySnapshot>() {

        @Override
        public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
            if (!documentSnapshots.isEmpty()) {
                int count = documentSnapshots.size();
                holder.updateLikesCount(count);
            } else {
                holder.updateLikesCount(0);
            }
        }
    });
    // Get Likes
    firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").document(currentUserId).addSnapshotListener(new EventListener<DocumentSnapshot>() {

        @Override
        public void onEvent(DocumentSnapshot documentSnapshot, FirebaseFirestoreException e) {
            if (documentSnapshot.exists()) {
                holder.blogLikeBtn.setImageDrawable(context.getDrawable(R.mipmap.action_like_accent));
            } else {
                holder.blogLikeBtn.setImageDrawable(context.getDrawable(R.mipmap.action_like_gray));
            }
        }
    });
    // Likes Feature
    holder.blogLikeBtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").document(currentUserId).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {

                @Override
                public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                    if (!task.getResult().exists()) {
                        Map<String, Object> likesMap = new HashMap<>();
                        likesMap.put("timestamp", FieldValue.serverTimestamp());
                        firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").document(currentUserId).set(likesMap);
                    } else {
                        firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").document(currentUserId).delete();
                    }
                }
            });
        }
    });
    holder.blogCommentBtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent commentIntent = new Intent(context, CommentsActivity.class);
            commentIntent.putExtra("blog_post_id", blogPostId);
            context.startActivity(commentIntent);
        }
    });
}
Also used : Task(com.google.android.gms.tasks.Task) HashMap(java.util.HashMap) FirebaseFirestoreException(com.google.firebase.firestore.FirebaseFirestoreException) Intent(android.content.Intent) ImageView(android.widget.ImageView) CircleImageView(de.hdodenhof.circleimageview.CircleImageView) View(android.view.View) RecyclerView(android.support.v7.widget.RecyclerView) TextView(android.widget.TextView) Date(java.util.Date) FirebaseFirestoreException(com.google.firebase.firestore.FirebaseFirestoreException) QuerySnapshot(com.google.firebase.firestore.QuerySnapshot) DocumentSnapshot(com.google.firebase.firestore.DocumentSnapshot) OnCompleteListener(com.google.android.gms.tasks.OnCompleteListener) NonNull(android.support.annotation.NonNull)

Example 3 with QuerySnapshot

use of com.google.firebase.firestore.QuerySnapshot in project PhotoBlog-Android-Blog-App by akshayejh.

the class HomeFragment method onCreateView.

@Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_home, container, false);
    blog_list = new ArrayList<>();
    blog_list_view = view.findViewById(R.id.blog_list_view);
    firebaseAuth = FirebaseAuth.getInstance();
    blogRecyclerAdapter = new BlogRecyclerAdapter(blog_list);
    blog_list_view.setLayoutManager(new LinearLayoutManager(container.getContext()));
    blog_list_view.setAdapter(blogRecyclerAdapter);
    blog_list_view.setHasFixedSize(true);
    if (firebaseAuth.getCurrentUser() != null) {
        firebaseFirestore = FirebaseFirestore.getInstance();
        blog_list_view.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                Boolean reachedBottom = !recyclerView.canScrollVertically(1);
                if (reachedBottom) {
                    loadMorePost();
                }
            }
        });
        Query firstQuery = firebaseFirestore.collection("Posts").orderBy("timestamp", Query.Direction.DESCENDING).limit(3);
        firstQuery.addSnapshotListener(getActivity(), new EventListener<QuerySnapshot>() {

            @Override
            public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
                if (!documentSnapshots.isEmpty()) {
                    if (isFirstPageFirstLoad) {
                        lastVisible = documentSnapshots.getDocuments().get(documentSnapshots.size() - 1);
                        blog_list.clear();
                    }
                    for (DocumentChange doc : documentSnapshots.getDocumentChanges()) {
                        if (doc.getType() == DocumentChange.Type.ADDED) {
                            String blogPostId = doc.getDocument().getId();
                            BlogPost blogPost = doc.getDocument().toObject(BlogPost.class).withId(blogPostId);
                            if (isFirstPageFirstLoad) {
                                blog_list.add(blogPost);
                            } else {
                                blog_list.add(0, blogPost);
                            }
                            blogRecyclerAdapter.notifyDataSetChanged();
                        }
                    }
                    isFirstPageFirstLoad = false;
                }
            }
        });
    }
    // Inflate the layout for this fragment
    return view;
}
Also used : Query(com.google.firebase.firestore.Query) FirebaseFirestoreException(com.google.firebase.firestore.FirebaseFirestoreException) LinearLayoutManager(android.support.v7.widget.LinearLayoutManager) DocumentChange(com.google.firebase.firestore.DocumentChange) View(android.view.View) RecyclerView(android.support.v7.widget.RecyclerView) Point(android.graphics.Point) QuerySnapshot(com.google.firebase.firestore.QuerySnapshot) RecyclerView(android.support.v7.widget.RecyclerView)

Example 4 with QuerySnapshot

use of com.google.firebase.firestore.QuerySnapshot in project FirebaseUI-Android by firebase.

the class FirestorePagingSource method loadSingle.

@NonNull
@Override
public Single<LoadResult<PageKey, DocumentSnapshot>> loadSingle(@NonNull LoadParams<PageKey> params) {
    final Task<QuerySnapshot> task;
    if (params.getKey() == null) {
        task = mQuery.limit(params.getLoadSize()).get(mSource);
    } else {
        task = params.getKey().getPageQuery(mQuery, params.getLoadSize()).get(mSource);
    }
    return Single.fromCallable(() -> {
        Tasks.await(task);
        if (task.isSuccessful()) {
            QuerySnapshot snapshot = task.getResult();
            PageKey nextPage = getNextPageKey(snapshot);
            if (snapshot.getDocuments().isEmpty()) {
                return toLoadResult(snapshot.getDocuments(), null);
            }
            return toLoadResult(snapshot.getDocuments(), nextPage);
        }
        throw task.getException();
    }).subscribeOn(Schedulers.io()).onErrorReturn(throwable -> new LoadResult.Error<>(throwable));
}
Also used : QuerySnapshot(com.google.firebase.firestore.QuerySnapshot) NonNull(androidx.annotation.NonNull)

Aggregations

QuerySnapshot (com.google.firebase.firestore.QuerySnapshot)4 FirebaseFirestoreException (com.google.firebase.firestore.FirebaseFirestoreException)3 RecyclerView (android.support.v7.widget.RecyclerView)2 View (android.view.View)2 DocumentChange (com.google.firebase.firestore.DocumentChange)2 Query (com.google.firebase.firestore.Query)2 Intent (android.content.Intent)1 Point (android.graphics.Point)1 NonNull (android.support.annotation.NonNull)1 LinearLayoutManager (android.support.v7.widget.LinearLayoutManager)1 ImageView (android.widget.ImageView)1 TextView (android.widget.TextView)1 NonNull (androidx.annotation.NonNull)1 OnCompleteListener (com.google.android.gms.tasks.OnCompleteListener)1 Task (com.google.android.gms.tasks.Task)1 DocumentSnapshot (com.google.firebase.firestore.DocumentSnapshot)1 CircleImageView (de.hdodenhof.circleimageview.CircleImageView)1 Date (java.util.Date)1 HashMap (java.util.HashMap)1