android recyclerview第一次启动时未加载

时间:2019-05-15 22:39:51

标签: java android android-recyclerview

我正在Android中使用Firestore。在我的片段中,我有一个recyclerview,可以从Firestore中获取数据,但是在首次启动应用程序时,recyclerview是空的,但是当我移至另一个片段并返回时,它会加载数据。

这是我的适配器类

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);
    }


}

 }

我的片段类

    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();
                    }
                }
            }

我希望片段在第一次启动时按预期加载。需要帮助...谢谢。

1 个答案:

答案 0 :(得分:0)

您是第一次在哪里设置适配器的?因为您应该在列表中获得元素后执行此操作

                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();
                }