android recyclerview not loading on first launch

44
May 16, 2019, at 7:30 PM

i am using firestore in android. in my fragment i have a recyclerview which fetch data from firestore but on first launch of app the recyclerview is empty but when i move to another fragment and come back , it get loaded with data.

This is my adapter class

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private List<ProductPost> product_list;
FirebaseFirestore firebaseFirestore;
FirebaseAuth auth;
private TextView cartCount;
private Context context;
private int previousPosition = 0;
private int itemInCart;
//pass textview and value of item in cart to constructor
public RecyclerAdapter (Context context, List<ProductPost> product_list, TextView cartCount, int itemInCart){
    this.cartCount = cartCount;
    this.product_list = product_list;
    this.itemInCart = itemInCart;
    this.context = context;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_main, parent, false);
    context = parent.getContext();
    firebaseFirestore = FirebaseFirestore.getInstance();
    auth = FirebaseAuth.getInstance();
    return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull final ViewHolder holder, @SuppressLint("RecyclerView") int position) {

    holder.setIsRecyclable(false);
    final String productID = product_list.get(position).ProductID;
    String image_uri = product_list.get(position).getImage();
    holder.retrieveImage(image_uri);
    //if user is authenticated, count number of document and attach the size to the view (floating button)
    if(auth.getCurrentUser() != null){
        final String currentUser = auth.getCurrentUser().getUid();
        firebaseFirestore.collection(currentUser).get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        int count = 0;
                        for (final QueryDocumentSnapshot document : task.getResult()){
                            count += Integer.parseInt(document.getString("qty"));
                            cartCount.setText(Integer.toString(count));
                        }
                    }
                });
    }
    holder.postImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(final View view) {
            holder.bookProgress.setVisibility(View.VISIBLE);
            firebaseFirestore.collection("All_Books").document(productID)
                    .get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                @Override
                public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                    if(task.isSuccessful()){
                        DocumentSnapshot documentSnapshot = task.getResult();
                        if(documentSnapshot != null){
                            String display_price = documentSnapshot.getString("book_price");
                            String display_name = documentSnapshot.getString("Name");
                            String display_title = documentSnapshot.getString("book_title");
                            String display_category = documentSnapshot.getString("category");
                            String display_image = documentSnapshot.getString("image");
                            String display_store = documentSnapshot.getString("store_name");
                            String display_description = documentSnapshot.getString("description");
                            Intent intent = new Intent().setClass(view.getContext(), BookDetails.class);
                            intent.putExtra("price", display_price);
                            intent.putExtra("name", display_name);
                            intent.putExtra("title", display_title);
                            intent.putExtra("image", display_image);
                            intent.putExtra("store", display_store);
                            intent.putExtra("category", display_category);
                            intent.putExtra("desc", display_description);
                            intent.putExtra("product_id", productID);
                            view.getContext().startActivity(intent);
                        }else{
                            holder.bookProgress.setVisibility(View.INVISIBLE);
                            Toast.makeText(context, "This book is finished in the store!", Toast.LENGTH_LONG).show();
                        }
                    }else{
                        String error = Objects.requireNonNull(task.getException()).getMessage();
                        Toast.makeText(context, error, Toast.LENGTH_LONG).show();
                        holder.bookProgress.setVisibility(View.INVISIBLE);
                    }
                }
            });
        }
    });
}
@Override
public int getItemCount() {
    return product_list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
    private View mview;
    private ImageView postImage;
    private ProgressBar bookProgress;
    TextView mainText;
    private ViewHolder(View itemView) {
        super(itemView);
        mview = itemView;
        postImage = mview.findViewById(R.id.product);
        bookProgress = mview.findViewById(R.id.bookProgress);
        mainText = mview.findViewById(R.id.mainText);
    }
    private void retrieveImage(String downloadUri){
        postImage = mview.findViewById(R.id.product);
        Glide.with(context).load(downloadUri).listener(new RequestListener<Drawable>() {
            @Override
            public boolean onLoadFailed(@android.support.annotation.Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
               mainText.setVisibility(View.GONE);
                return false;
            }
            @Override
            public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                mainText.setVisibility(View.GONE);
                return false;
            }
        })
                .into(postImage);
    }

}
 }

my fragment class

    Query.addSnapshotListener(new EventListener<QuerySnapshot>() {
        @Override
        public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException e) {
            if (e != null) {
                return;
            }
            if(queryDocumentSnapshots != null && !queryDocumentSnapshots.isEmpty()){
                for (DocumentChange doc : queryDocumentSnapshots.getDocumentChanges()) {
                    if (doc.getType() == DocumentChange.Type.ADDED) {
                        String productID = doc.getDocument().getId();
                        ProductPost productPost = doc.getDocument().toObject(ProductPost.class).withId(productID);
                        product_list.add(productPost);
                        productRecyclerAdapter.notifyDataSetChanged();
                    }
                }
            }

i want fragment to load on first launch as expected. need help...Thanks in advance.

Answer 1

where did you set your Adapter at the first time ? because you should do it after you get element in your list

                if (doc.getType() == DocumentChange.Type.ADDED) {
                    String productID = doc.getDocument().getId();
                    ProductPost productPost = doc.getDocument().toObject(ProductPost.class).withId(productID);
                    product_list.add(productPost);
                    //set your adapter here first 
                    productRecyclerAdapter.notifyDataSetChanged();
                }
READ ALSO
How to parse HH:mm:ss without hours?

How to parse HH:mm:ss without hours?

I have a string with format like: "2h 33m 50s"If hours reach zero this string changes to: "33m 50s"

31
Is JDK 8’s new strategy for dealing with HashMap collisions(tree instead of list) need only for those who is not able to write a good hashcode()?

Is JDK 8’s new strategy for dealing with HashMap collisions(tree instead of list) need only for those who is not able to write a good hashcode()?

In Java 8, HashMap replaces linked list with a binary tree when the number of elements in a bucket reaches certain threshold

45
How to disable Jackson from deserializing an Instant from epoch millis?

How to disable Jackson from deserializing an Instant from epoch millis?

I am developing an API using Spring Boot and am using Jackson for payload (de)serializationI want to deserialize an ISO-8601 formatted datetime into a java

17