如何使用searchView从Firestore中搜索数据列表

时间:2018-07-08 13:39:15

标签: android search google-cloud-firestore searchview

我已经成功地从FireStore检索了数据,我想使用SearchView搜索数据列表,但是当我尝试在Searchview中搜索时,它在recyclerView中没有显示任何内容。

这是我主要活动的代码。我使用查询检索数据列表,并在回收站视图中显示。

    public class MainActivity extends AppCompatActivity {

    private final static String TAG = MainActivity.class.getSimpleName();

    private RecyclerView recyclerView;

    private FirebaseAuth mAuth;
    private FirebaseFirestore db;
    private FoodAdapter mAdapter;
    SearchView searchView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mAuth = FirebaseAuth.getInstance();
        db = FirebaseFirestore.getInstance();


        // Force Login
        if (mAuth.getCurrentUser() == null || mAuth.getCurrentUser().getEmail().isEmpty()) {
            Intent intent = new Intent(this, Login.class);
            startActivity(intent);
            finish();
        }

        recyclerView = findViewById(R.id.recycler_home);   

        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        searchView = findViewById(R.id.search);

        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        searchView.setMaxWidth(Integer.MAX_VALUE);

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {

                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                getSearch(newText);
                return false;

            }
        });


        mAdapter = new FoodAdapter(new FoodAdapter.OnFoodClickListener() {
            @Override
            public void OnClick(FoodModel food) {
                Intent intent = new Intent(MainActivity.this, FoodActivity.class);
                intent.putExtra("id", food.getId());
                startActivity(intent);
            }

        getFoodData();

        recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));
        recyclerView.setAdapter(mAdapter);

    }




    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        getFoodData();
    }

public void getSearch(String s){

    mAdapter.clear();

    Query que = db.collection("Food");

        que.whereEqualTo("title", s);

        que

            .get()
            .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
                @Override
                public void onSuccess(QuerySnapshot documentSnapshots) {
                    if (!documentSnapshots.isEmpty()) {
                        for (DocumentSnapshot docSnap : documentSnapshots.getDocuments()) {
                            FoodModel model = docSnap.toObject(FoodModel.class);
                            model.setId(docSnap.getId());
                            loadSticker(model);

                        }
                    }
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.d(TAG, e.getLocalizedMessage());
                }
            });
}


    public void getFoodData() {

        mAdapter.clear();

        Query query = db.collection(“Food”);

        query
                .get()
                .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
                    @Override
                    public void onSuccess(QuerySnapshot documentSnapshots) {
                        if (!documentSnapshots.isEmpty()) {
                            for (DocumentSnapshot docSnap : documentSnapshots.getDocuments()) {
                                FoodModel model = docSnap.toObject(FoodModel.class);
                                model.setId(docSnap.getId());
                                loadSticker(model);

                            }
                        }
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Log.d(TAG, e.getLocalizedMessage());
                    }
                });
    }

    public void loadSticker(final FoodModel foodModel) {

        db
                .collection("beverage")
                .whereEqualTo("name", foodModel.getBeverage())
                .get()
                .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
                    @Override
                    public void onSuccess(QuerySnapshot documentSnapshots) {

                        if (documentSnapshots.getDocuments().get(0).exists()) {
                            BeverageModel model = documentSnapshots.getDocuments().get(0).toObject(BeverageModel.class);

                            FoodModel newFoodModel = foodModel;
                            newFoodModel.setSticker(model.getSticker());
                            mAdapter.addItem(newFoodModel);
                        }
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Log.d(TAG, e.getLocalizedMessage());
                    }
                });
    }
}

这是适配器代码,我将其应用于searchView的过滤器。谁都知道我的适配器代码错误。

    public class FoodAdapter extends RecyclerView.Adapter<FoodAdapter.FoodViewHolder> {

    private List<FoodModel> foodModels;
    private List<FoodModel>foodModelsList;
    private OnFoodClickListener listener;


    public FoodAdapter(OnFoodClickListener listener) {
        foodModels = new ArrayList<>();
        this.foodModelsList = foodModels;
        this.listener = listener;
    }

    @Override
    public FoodViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_holder_food, parent, false);
        return new FoodViewHolder(view);
    }

    @Override
    public void onBindViewHolder(FoodViewHolder holder, int position) {

        FooModel model = foodModels.get(position);

        holder.title.setText(model.getTitle());
        holder.description.setText(model.getDescription());

            Picasso.get().load(model.getSticker()).into(holder.sticker);
    }

    @Override
    public int getItemCount() {
        return foodModels.size();
    }

    public void addItem(FoodModel food){
        foodModels.add(food);
        notifyDataSetChanged();
    }


    class FoodViewHolder extends RecyclerView.ViewHolder {

        private TextView name, description;
        private ImageView sticker;

        FoodViewHolder(View itemView) {
            super(itemView);

            title = itemView.findViewById(R.id.tv_title);
            sticker = itemView.findViewById(R.id.img_sticker);
            description = itemView.findViewById(R.id.tv_description);


            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    int position = getAdapterPosition();
                    listener.OnClick(foodModels.get(position));
                }
            });

         }
    }

    public interface OnFoodClickListener{
        void OnClick(FoodModel food);
    }
}

0 个答案:

没有答案