0

I'm using the library Material Search Bar to search my Firebase Database, but it doesn't work.

Right here is the layout and it is assumed that when I click on the search bar should give me some suggestions and also to look for products but it is not

View

My Firebase Database

Firebase DataBase

Here is my Home.java where i put the searchBar

public class Home extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

FirebaseDatabase database;
DatabaseReference product;

TextView userName;

RecyclerView recycler_prod;
RecyclerView.LayoutManager layoutManager;

FirebaseRecyclerAdapter<Product,ProductViewHolder> adapter;

FirebaseRecyclerAdapter<Product, ProductViewHolder> searchadapter;

MaterialSearchBar searchBar;
String ProductId = "";
List<String> suggestList = new ArrayList<>();


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    database=FirebaseDatabase.getInstance();
    product=database.getReference("Product");

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
    View headerView = navigationView.getHeaderView(0);
    userName= headerView.findViewById(R.id.idUserName);
    userName.setText(Common.currentuser.getName());

    recycler_prod = findViewById(R.id.recycler_card);
    recycler_prod.setHasFixedSize(true);
    layoutManager = new LinearLayoutManager(this);
    recycler_prod.setLayoutManager(layoutManager);

    loadProducts();

    searchBar =  findViewById(R.id.searchBar);
    searchBar.setPlaceHolder("Productos");
    loadSuggest();
    searchBar.setLastSuggestions(suggestList);
    searchBar.setCardViewElevation(10);
    searchBar.addTextChangeListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            List<String> suggest = new ArrayList<String>();
            for (String search : suggestList) {
                if (search.toLowerCase().contains(searchBar.getText().toLowerCase()))
                    suggest.add(search);
            }
            searchBar.setLastSuggestions(suggest);

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });
    searchBar.setOnSearchActionListener(new MaterialSearchBar.OnSearchActionListener() {
        @Override
        public void onSearchStateChanged(boolean enabled) {
            if (!enabled)
                recycler_prod.setAdapter(adapter);
        }

        @Override
        public void onSearchConfirmed(CharSequence text) {
            startSearch(text);
        }

        @Override
        public void onButtonClicked(int buttonCode) {

        }
    });




}

private void startSearch(CharSequence text) {
    searchadapter = new FirebaseRecyclerAdapter<Product, ProductViewHolder>(
            Product.class,
            R.layout.card_item,
            ProductViewHolder.class,
            product.orderByChild("Name").equalTo(text.toString())
    ) {
        @Override
        protected void populateViewHolder(ProductViewHolder viewHolder, Product model, int position) {
            viewHolder.txtProductName.setText(model.getName());
            Picasso.get().load(model.getImage())
                    .into(viewHolder.imageProductView);
            final Product local = model;

            viewHolder.setItemClickListener(new ItemClickListener() {
                @Override
                public void onClick(View view, int position, boolean isLongClick) {
                    Intent details = new Intent(Home.this, ProductDetail.class);
                    details.putExtra("ProductId", searchadapter.getRef(position).getKey());
                    startActivity(details);
                }
            });
        }
    };
    recycler_prod.setAdapter(searchadapter);
}

private void loadSuggest() {
    product.orderByChild("ProductId").equalTo(ProductId)
            .addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    for(DataSnapshot postSnapshot:dataSnapshot.getChildren()){
                        Product item = postSnapshot.getValue(Product.class);
                        suggestList.add(item.getName());
                    }
                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                }
            });


}

private void loadProducts() {
    adapter = new FirebaseRecyclerAdapter<Product, ProductViewHolder>(Product.class,
            R.layout.card_item,
            ProductViewHolder.class,
            product) {
        @Override
        protected void populateViewHolder(ProductViewHolder holder, Product model, int position) {
            holder.txtProductName.setText(model.getName());
            holder.txtProductDesc.setText(model.getDescription());
            holder.txtProductPrice.setText("$" + model.getPrice());
            Picasso.get().load(model.getImage())
                    .into(holder.imageProductView);
            final Product clickItem = model;
            holder.setItemClickListener(new ItemClickListener() {
                @Override
                public void onClick(View view, int position, boolean isLongClick) {
                    Intent details = new Intent(Home.this, ProductDetail.class);
                    details.putExtra("ProductId", adapter.getRef(position).getKey());
                    startActivity(details);
                }
            });
        }

    };
    recycler_prod.setAdapter(adapter);
}


@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.home, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_search) {
        // Handle the camera action
    } else if (id == R.id.nav_map) {
        Intent mapa = new Intent(Home.this,Maps.class);
        startActivity(mapa);
    } else if (id == R.id.nav_log_out) {

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}
}

My Product.java Model

public class Product {
private String Description, Name, Image,Price,Link;

public Product() {
}

public Product(String description, String name, String image, String price, String link) {
    Description = description;
    Name = name;
    Image = image;
    Price = price;
    Link = link;
}

public String getLink() {
    return Link;
}

public void setLink(String link) {
    Link = link;
}

public String getDescription() {
    return Description;
}

public void setDescription(String description) {
    Description = description;
}

public String getName() {
    return Name;
}

public void setName(String name) {
    Name = name;
}

public String getImage() {
    return Image;
}

public void setImage(String image) {
    Image = image;
}

public String getPrice() {
    return Price;
}

public void setPrice(String price) {
    Price = price;
}
 }

My ProductViewHolder.java

public class ProductViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

public TextView txtProductName,txtProductDesc,txtProductPrice;
public ImageView imageProductView;
private ItemClickListener itemClickListener;

public ProductViewHolder(@NonNull View itemView) {
    super(itemView);

    txtProductName = itemView.findViewById(R.id.name);
    txtProductDesc = itemView.findViewById(R.id.description);
    txtProductPrice = itemView.findViewById(R.id.price);
    imageProductView = itemView.findViewById(R.id.thumbnail);

    itemView.setOnClickListener(this);

}

public void setItemClickListener(ItemClickListener itemClickListener) {
    this.itemClickListener = itemClickListener;
}

@Override
public void onClick(View v) {
    itemClickListener.onClick(v,getAdapterPosition(),false);
}
 }

Thank you for your attention

KENdi
  • 7,576
  • 2
  • 16
  • 31
  • i think you get help from this link. It will filter your database items and give you suggestions when you click on searchbar https://www.androidhive.info/2017/11/android-recyclerview-with-search-filter-functionality/ one more...https://stackoverflow.com/questions/30369246/implementing-searchview-as-per-the-material-design-guidelines – Rishav Singla Nov 19 '18 at 09:22
  • Check **[this](https://stackoverflow.com/questions/50682046/applying-word-stemming-in-searchview-for-fetch-data-from-firebase-database)** out. – Alex Mamo Nov 19 '18 at 10:38

1 Answers1

0

In your startSearch method, replace your .equalto with .startAt. See if it works

Abhishek Dutt
  • 1,308
  • 7
  • 14
  • 24