简体   繁体   English

单击按钮时如何更改 Firestore 查询?

[英]How to change Firestore query when clicking button?

I want to change firestore query parameter when clicking button.单击按钮时,我想更改 Firestore 查询参数。 For example, my query is this by default:例如,我的查询默认是这样的:

db.collection("Posts").whereEqualTo("postCategory", "Business").orderBy("createdAt", Query.Direction.DESCENDING);

But when I click "Economy" button query needs to be changed to this and show different post results:但是当我单击“经济”按钮时,查询需要更改为此并显示不同的帖子结果:

db.collection("Posts").whereEqualTo("postCategory", "Economy").orderBy("createdAt", Query.Direction.DESCENDING);

I tried to create String called selectedCategory and changed the value as I clicked the button but it had no effect as I call it in onCreateView and it is called only once.我尝试创建名为 selectedCategory 的字符串,并在单击按钮时更改了值,但它没有任何效果,因为我在 onCreateView 中调用它并且只调用了一次。 I also created indexes in Firestore console so it is not index related problem.我还在 Firestore 控制台中创建了索引,因此它不是与索引相关的问题。 There are 2 recyclerviews in my fragment;我的片段中有 2 个回收站视图; one of them holds buttons for category and other shows posts.其中一个拥有类别和其他节目帖子的按钮。 I have been working on this problem for a while and any help is appreciated.我一直在研究这个问题一段时间,任何帮助表示赞赏。 Thanks谢谢

Edit:编辑:

TrendCategoryTagsAdapter.java TrendCategoryTagsAdapter.java

public class TrendCategoryTagsAdapter extends FirestoreRecyclerAdapter<CategorySelection, TrendCategoryTagsAdapter.TrendCategoryTagsHolder> {

    Context context;

    CategoryTagClicked categoryTagClicked;

    int row_index;

    public TrendCategoryTagsAdapter(@NonNull FirestoreRecyclerOptions<CategorySelection> options, Context context, CategoryTagClicked categoryTagClicked) {
        super(options);
        this.context = context;
        this.categoryTagClicked = categoryTagClicked;
    }

    @Override
    protected void onBindViewHolder(@NonNull final TrendCategoryTagsHolder holder, final int position, @NonNull CategorySelection model) {
        holder.categoryNameText.setText(model.getCategoryName());

        holder.categoryNameContainer.setOnClickListener(view -> {
            String categoryName = holder.categoryNameText.getText().toString();
            categoryTagClicked.onCategoryClicked(categoryName);
            row_index = position;
            notifyDataSetChanged();
        });

        if (row_index == position) {
            holder.categoryNameContainer.setBackground(ContextCompat.getDrawable(context, R.drawable.black_rounded_bg));
        } else {
            holder.categoryNameContainer.setBackground(ContextCompat.getDrawable(context, R.drawable.grey_rounded_bg));
        }
    }

    @NonNull
    @Override
    public TrendCategoryTagsHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(context).inflate(R.layout.trendcategory_cell, parent, false);
        return new TrendCategoryTagsAdapter.TrendCategoryTagsHolder(v);
    }

    public static class TrendCategoryTagsHolder extends RecyclerView.ViewHolder {
        RelativeLayout categoryNameContainer;
        TextView categoryNameText;

        public TrendCategoryTagsHolder(@NonNull View itemView) {
            super(itemView);
            categoryNameContainer = itemView.findViewById(R.id.categoryNameContainer);
            categoryNameText = itemView.findViewById(R.id.categoryNameText);
        }
    }

}

TrendingFragment.java TrendingFragment.java

public class TrendingFragment extends Fragment implements CategoryTagClicked {

    RecyclerView trendPostRV, trendingCategoryRV;
    public TextView noPostTV;

    FirebaseFirestore db = FirebaseFirestore.getInstance();
    CollectionReference categoryRef, postRef;

    TrendCategoryTagsAdapter trendCategoryTagsAdapter;
    TrendingPostAdapter trendingPostAdapter;

    String selectedCategory = "Art";

    public TrendingFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_trending, container, false);

        trendPostRV = view.findViewById(R.id.trendPostRV);
        trendingCategoryRV = view.findViewById(R.id.trendingCategoryRV);
        noPostTV = view.findViewById(R.id.noPostTV);

        setUpTrendCategoryTagsRV();
        setUpTrendingPostRV();
        checkIfDataNull();
        // Inflate the layout for this fragment
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        trendCategoryTagsAdapter.startListening();
        trendingPostAdapter.startListening();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        trendCategoryTagsAdapter.stopListening();
        trendingPostAdapter.stopListening();
    }

    private void setUpTrendCategoryTagsRV() {
        categoryRef = db.collection("Categories");

        Query query = categoryRef.orderBy("categoryName", Query.Direction.ASCENDING);

        FirestoreRecyclerOptions<CategorySelection> options = new FirestoreRecyclerOptions.Builder<CategorySelection>()
                .setQuery(query, CategorySelection.class)
                .build();

        trendCategoryTagsAdapter = new TrendCategoryTagsAdapter(options, getContext(), this);

        trendingCategoryRV.setNestedScrollingEnabled(false);

        final LinearLayoutManager trendingTagsLM = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
        trendingCategoryRV.setLayoutManager(trendingTagsLM);
        trendingCategoryRV.setAdapter(trendCategoryTagsAdapter);
        trendCategoryTagsAdapter.notifyDataSetChanged();
    }

    public void setUpTrendingPostRV() {
        postRef = db.collection("Posts");

        Query query = postRef.whereEqualTo("postCategory", selectedCategory).orderBy("createdAt", Query.Direction.DESCENDING);

        FirestoreRecyclerOptions<Post> options = new FirestoreRecyclerOptions.Builder<Post>()
                .setQuery(query, Post.class)
                .build();

        trendingPostAdapter = new TrendingPostAdapter(options, getContext());

        trendPostRV.setNestedScrollingEnabled(false);

        LinearLayoutManager trendingPostLM = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        trendPostRV.setLayoutManager(trendingPostLM);
        trendPostRV.setAdapter(trendingPostAdapter);
        trendingPostAdapter.notifyDataSetChanged();
    }

    private void checkIfDataNull() {
        db.collection("Posts").whereEqualTo("postCategory", selectedCategory).get().addOnCompleteListener(task -> {
            if (task.isSuccessful() && task.getResult() != null) {
                if (task.getResult().size() == 0) {
                    noPostTV.setVisibility(View.VISIBLE);
                    trendPostRV.setVisibility(View.GONE);
                } else {
                    noPostTV.setVisibility(View.GONE);
                    trendPostRV.setVisibility(View.VISIBLE);
                }
            } else {
                Log.d("TAG", "Error getting documents: ", task.getException());
            }
        });
    }

    @Override
    public void onCategoryClicked(String category) {
        selectedCategory = category;
        Toast.makeText(getContext(), selectedCategory, Toast.LENGTH_SHORT).show();
    }
}

CategoryTagClicked.java (Interface) CategoryTagClicked.java(接口)

public interface CategoryTagClicked {
    void onCategoryClicked(String category);
}

Brief explanation of what I do:简要说明我的工作:

Whenever I click on category button I pass the text of the button (in this case category name) to the selectedCategory string inside TrendingFragment.每当我单击类别按钮时,我都会将按钮的文本(在本例中为类别名称)传递给 TrendingFragment 中的 selectedCategory 字符串。 String selectedCategory is a parameter for query in setUpTrendingPostRV function. String selectedCategory 是 setUpTrendingPostRV function 中查询的参数。 The problem is it only shows results after changing fragments but I want changes to take place immediately after I click the button.问题是它只在更改片段后显示结果,但我希望在单击按钮后立即进行更改。

I finally found what was an issue.我终于找到了问题所在。 It seems I needed to update my options inside onCategoryClicked interface.看来我需要在 onCategoryClicked 界面中更新我的选项。

@Override
    public void onCategoryClicked(String category) {
        selectedCategory = category;
        Toast.makeText(getContext(), selectedCategory, Toast.LENGTH_SHORT).show();

        Query newQuery = postRef.whereEqualTo("postCategory", selectedCategory).orderBy("createdAt", Query.Direction.DESCENDING);

        FirestoreRecyclerOptions<Post> options = new FirestoreRecyclerOptions.Builder<Post>()
                .setQuery(newQuery, Post.class)
                .build();

        trendingPostAdapter.updateOptions(options);

        checkIfDataNull();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM