There is a database with categories, each category has a list of values ​​inside. How can I make it so that when a category is selected, a list of items that fall into the selected category is displayed? Now my category names are displayed using RecyclerView.

reference = FirebaseDatabase.getInstance().getReference().child("products"); reference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { list = new ArrayList<ProductModel>(); for(DataSnapshot dataSnapshot1: dataSnapshot.getChildren()){ // Iterable<DataSnapshot> ProductChild = dataSnapshot1.getChildren(); ProductModel p = new ProductModel(); p.setProductName(dataSnapshot1.getKey()); list.add(p); } adapter = new ProductAdapter(ProductSelectionActivity.this,list); recyclerView.setAdapter(adapter); } 

For example, a person chooses the category "Dairy products". And I need to display a list of products included in the selected category.

enter image description here

Ie I need to handle the press and somehow compare? Please tell me, because newbie, just started learning Android and the first time I work with Firebase.

Abstract class processing click on the category:

 public abstract class RecyclerClickListener implements RecyclerView.OnItemTouchListener{ private GestureDetector gestureDetector;// используется, чтобы понять, произошел клик private GestureDetector.OnGestureListener gestureListener = new GestureDetector.SimpleOnGestureListener() { @Override public boolean onSingleTapUp(MotionEvent e) { return true; } }; public RecyclerClickListener(Context context) { gestureDetector = new GestureDetector(context, gestureListener); } @Override public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) { if (gestureDetector.onTouchEvent(e)) { View clickedChild = rv.findChildViewUnder(e.getX(), e.getY()); // findChildViewUnder используется для определения нажатого элемента if (clickedChild != null && !clickedChild.dispatchTouchEvent(e)) { int clickedPosition = rv.getChildAdapterPosition(clickedChild); // getChildAdapterPosition - определение позиции if (clickedPosition != RecyclerView.NO_POSITION) { onItemClick(rv, clickedChild, clickedPosition); return true; } } } return false; } @Override public void onTouchEvent(RecyclerView rv, MotionEvent e) { } public abstract void onItemClick(RecyclerView recyclerView, View itemView, int position);} 

At the moment I have a list with categories of products: Dairy products, fish, meat, etc.

 public class ProductSelectionActivity extends AppCompatActivity { private RecyclerView recyclerView; private ArrayList<ProductModel>list; private ProductAdapter adapter; private DatabaseReference reference; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_product_selection); recyclerView = (RecyclerView) findViewById(R.id.product_list); LinearLayoutManager llm = new LinearLayoutManager(this); llm.setOrientation(LinearLayoutManager.VERTICAL); recyclerView.setLayoutManager(llm); recyclerView.setHasFixedSize(true); recyclerView.addOnItemTouchListener(new RecyclerClickListener(this) { @Override public void onItemClick(RecyclerView recyclerView, View itemView, final int position) { Toast.makeText(ProductSelectionActivity.this, "Click" , Toast.LENGTH_SHORT).show(); } @Override public void onRequestDisallowInterceptTouchEvent(boolean b) { } }); reference = FirebaseDatabase.getInstance().getReference().child("products"); reference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { list = new ArrayList<ProductModel>(); for(DataSnapshot dataSnapshot1: dataSnapshot.getChildren()){ ProductModel p = new ProductModel(); p.setProductName(dataSnapshot1.getKey()); list.add(p); } adapter = new ProductAdapter(ProductSelectionActivity.this,list); recyclerView.setAdapter(adapter); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { Toast.makeText(ProductSelectionActivity.this, "Ooops", Toast.LENGTH_SHORT).show(); } }); }} 

And now I need to click on the category to open a list with products in this category. How to do it?

  • By pressing. You transfer the put extra name to the key of this category along with the position. On another fragment / activation you catch this name and stick it in the same query. And why so you can press clicks, when you can do it through the interface and process everything directly in the fragment. - Romanovitch
  • @Romanych and how exactly to process through the interface? - Famous
  • four
    Possible duplicate question: Firebase data retrieval - Ivan Vovk
  • @IvanVovk, as a novice developer, I was not very clear about your answer, so I asked the question again. - Famous
  • If the answer is not very clear, then you need to clarify, and not create a new question, which will give exactly the same not very clear answer. - Enikeyschik

1 answer 1

You have FirebaseDatabase.getInstance().getReference().child("products"); where "products" gives an array of your json data. Read about Firebase examples on the Internet in bulk.

about click: I think it's easier to process click like this: create an interface

 public interface ItemClickListener { void onItemClick(int position); } 

then write in the adapter

 private static ItemClickListener listener; void setOnItemClickListener (ItemClickListener listener){ Adapter.listener = listener; } 

and in your ViewHolder

 itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (Adapter.listener != null){ Adapter.listener.onItemClick(getAdapterPosition()); } } }); 

then go to your fragment or activity and implement your own interface

 Fragment implements ItemClickListener 

in OnCreateView install the adapter the listener

 adapter.setOnItemClickListener(this); 

Well, you process the click:

 @Override public void onItemClick(int position) { //здесь можно передать аргументы другому фрагменту, но мы просто перейдем в другую активность Intent intent = new Intent(getActivity()//или this , DetailActivity.class); //для простоты примера можно передать position //не забывайте она начинается с 0 intent.putExtra("my_key", position); // здесь можно передать list.get(position).getKey() где под этим понимается ключ , который вы передаете, //например название категории в вашем случае для считывания даных в самой категории //или это может быть просто нажатая позиция 0, 1, 2 или 3 итд , и там дальше на //другом конце принимаете и вставляете так как вам нужно тут уже думайте сами как вам удобнее*/ startActivity(intent); 

And then in another activity we accept this position and derive our data from it.

 private int position; Bundle bundle = getIntent().getExtras(); if(bundle != null){ position = bundle.getInt("position"); } 

here we got the position that was clicked and then we set our data on it

 switch (position){ case 0: GetDataFirebase("Бакалея"); break; case 1: GetDataFirebase("Гречка"); break; } 

Further String position called for understanding.

  public void GetDataFirebase(String position){ DatabaseReference DBR = FirebaseDatabase.getInstance().getReference().child(position); 

That is, we thrust the name of the table, then we build the POJO in accordance with the structure of the class "Grocery" - and display it in RecyclerView

 String name итд..геттеры сеттеры. 

And that's all. Should work.

Better yet, simply pass the String key and insert it without reference to the position. But here I just showed an approximate course of action.

  • And in the new activation, I add recyclerview and prescribe in the class addValueEventLisneter? Or not ? - Famous