Can anyone help me to retrieve data from the node "foods" and put it in the RecyclerView. These are the file I've been working on but it turns out to be an empty list. I have viewed a tutorial on Internet but most of them were with an older version of Firebase. Recently, Firebase UI has been updated and the data binding process has changed to their new FirebaseRecyclerAdapter structure
This is my database structure:
"foods" : {
"AntipastoSalad" : {
"duration" : "30",
"img" : "https://firebasestorage.googleapis.com/v0/b/mealplanner-ec8ca.appspot.com/o/res%2Fsalad.jpg?alt=media&token=257d4392-8a1f-4fb7-84b5-b63abb4643f4",
"name" : "Antipasto salad",
"type" : "Salad"
},
This is my activity:
private RecyclerView mRecycleView;
private Query query;
private FirebaseRecyclerOptions<Meal> options;
private DatabaseReference mDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food_list_row);
mDatabase = FirebaseDatabase.getInstance().getReference().child("foods");
//Recycle View
mRecycleView = (RecyclerView) findViewById(R.id.meal_items);
mRecycleView.setHasFixedSize(true);
mRecycleView.setLayoutManager(new LinearLayoutManager(this));
}
#Override
protected void onStart() {
super.onStart();
query = FirebaseDatabase.getInstance().getReferenceFromUrl("https://mealplanner-ec8ca.firebaseio.com/foods/AntipastoSalad");
options = new FirebaseRecyclerOptions.Builder<Meal>()
.setQuery(query, Meal.class)
.build();
FirebaseRecyclerAdapter<Meal, FoodListRowActivity.MealRowHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Meal, FoodListRowActivity.MealRowHolder>(
options) {
#Override
public FoodListRowActivity.MealRowHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.food_row, parent, false);
return new FoodListRowActivity.MealRowHolder(v);
}
#Override
protected void onBindViewHolder(FoodListRowActivity.MealRowHolder holder, int position, Meal current) {
holder.setTitle(current.getName());
String duration = current.getDuration() + "min";
holder.setDuration(duration);
}
};
//Populate Item into Adapter
mRecycleView.setAdapter(firebaseRecyclerAdapter);
mRecycleView.addOnItemTouchListener(new RecycleViewItemClickListener(this, mRecycleView, new RecycleViewItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Intent viewMeal = new Intent(FoodListRowActivity.this, CookingInstructionActivity.class);
startActivity(viewMeal);
}
#Override
public void onLongItemClick(View view, int position) {
//TODO: DELETE
}
}));
}
public static class MealRowHolder extends RecyclerView.ViewHolder {
View mView;
public MealRowHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setTitle(String title) {
TextView foodTitle = (TextView) mView.findViewById(R.id.list_item_foodList_name);
foodTitle.setText(title);
}
public void setDuration(String title) {
TextView foodDuration = (TextView) mView.findViewById(R.id.list_item_foodList_calories);
foodDuration.setText(title);
}
}
}
and class structure:
public class Meal{
private String img;
private String duration;
private String name;
private String instruction;
public Meal(){
}
public Meal (String img, String duration, String name, String instruction){
this.img = img;
this.name = name;
this.duration = duration;
this.instruction = instruction;
}
public void update(String duration, String name, String instruction)
{
this.name = name;
this.duration = duration;
this.instruction = instruction;
}
public String getName(){
return name;
}
public String getDuration() {
return duration;
}
public String getInstruction() {
return instruction;
}
public String getImg(){return img;}
The query specified in the setQuery() method should be a reference to the root of the list you want to show in the RecyclerView, so like this:
query = FirebaseDatabase.getInstance().getReference().child("foods");
You also need to call startListening() on the adapter to instruct it to start retrieving data from the database.
From the FirebaseRecyclerAdapter lifecycle documentation:
The FirebaseRecyclerAdapter uses an event listener to monitor changes to the Firebase query. To begin listening for data, call the startListening() method. You may want to call this in your onStart() method. Make sure you have finished any authentication necessary to read the data before calling startListening() or your query will fail.
#Override protected void onStart() {
super.onStart();
adapter.startListening();
}
Similarly, the stopListening() call removes the event listener and all data in the adapter. Call this method when the containing Activity or Fragment stops:
#Override protected void onStop() {
super.onStop();
adapter.stopListening();
}
Please override getItemCount() method of FirebaseRecyclerAdapter.
#Override
public int getItemCount() {
return 1;
}
Reference.
This is how I'm retrieving my data in recyclerview using Firebase UI:
private FirebaseRecyclerAdapter<TaskPOJO, TaskViewHolder> adapter;
private void loadTasks() {
database = FirebaseDatabase.getInstance();
tasks = database.getReference("Tasks");
adapter = new FirebaseRecyclerAdapter<TaskPOJO, TaskViewHolder>(TaskPOJO.class, R.layout.task_item, TaskViewHolder.class, tasks) {
#Override
protected void populateViewHolder(TaskViewHolder viewHolder, final TaskPOJO model, int position) {
Log.wtf("valueTEst", "populateViewHolder: "+model.toString() );
Log.wtf("TEstScript1", "populateViewHolder: "+model.getTitle() );
viewHolder.title.setText(model.getTitle());
viewHolder.desc.setText(model.getDescripttion()+"\n");
viewHolder.remaining.setText(model.getRemaining()+"/"+model.getPoint());
viewHolder.points.setText("Points "+model.getRemaining());
Glide.with(viewHolder.title.getContext())
.load(model.getImage())
.into(viewHolder.image);
viewHolder.setClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
Toast.makeText(getActivity(), "" /*+ model.getTitle()*/, Toast.LENGTH_SHORT).show();
Intent TaskPOJODetail = new Intent(getActivity(), Main.class);
TaskPOJODetail.putExtra("value","detail");
TaskPOJODetail.putExtra("taskId",adapter.getRef(position).getKey());
startActivity(TaskPOJODetail);
}
});
}
};
progressBar.setVisibility(View.GONE);
recyclerViewTasks.setAdapter(adapter);
}
this is my firebase structure :
hope this will help you.
Related
This question already has an answer here:
Firebase Android ListView not being displayed
(1 answer)
Closed 1 year ago.
I am an android developer beginner, I am having a problem fetch files from firestore recycle view in the main activity but I can fetch files from fragments.
This is my main activity
public class FoodInfoActivity extends AppCompatActivity {
RecyclerView recyclerView1,recyclerView2;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference notebookRef;
private NoteAdapter adapter;
FirebaseAuth fAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food_info);
fAuth = FirebaseAuth.getInstance();
setUpRecyclerView();
}
private void setUpRecyclerView() {
notebookRef = db.collection("FoodInside");
Query query = notebookRef;
FirestoreRecyclerOptions<FoodAdapter> options = new FirestoreRecyclerOptions.Builder<FoodAdapter>()
.setQuery(query, FoodAdapter.class)
.build();
adapter = new NoteAdapter(options);
RecyclerView recyclerView = findViewById(R.id.fi);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
}
}
This is my Note adapter where i use model class to fetch file
public class NoteAdapter extends FirestoreRecyclerAdapter<FoodAdapter, NoteAdapter.NoteHolder> {
public NoteAdapter(#NonNull FirestoreRecyclerOptions<FoodAdapter> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull NoteHolder holder, int position, #NonNull FoodAdapter foodAdapter) {
holder.textViewTitle.setText(foodAdapter.getRestaurant());
holder.textViewDescription.setText(foodAdapter.getItem());
holder.textViewPriority.setText(String.valueOf(foodAdapter.getPrice()));
}
#NonNull
#Override
public NoteHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.food_recycle_layout,
parent, false);
return new NoteHolder(v);
}
class NoteHolder extends RecyclerView.ViewHolder {
TextView textViewTitle;
TextView textViewDescription;
TextView textViewPriority;
public NoteHolder(View itemView) {
super(itemView);
textViewTitle = itemView.findViewById(R.id.textView95a);
textViewDescription = itemView.findViewById(R.id.textView123a);
textViewPriority = itemView.findViewById(R.id.textView124a);
}
}
}
This is my adapter class ,
public class FoodAdapter {
String Restaurant;
String Item;
String Price;
String item_id;
public FoodAdapter() {
}
public FoodAdapter(String restaurant, String item, String price,String item_id) {
Restaurant = restaurant;
Item = item;
Price = price;
this.item_id = item_id;
}
public String getRestaurant() {
return Restaurant;
}
public void setRestaurant(String restaurant) {
Restaurant = restaurant;
}
public String getItem() {
return Item;
}
public void setItem(String item) {
Item = item;
}
public String getPrice() {
return Price;
}
public void setPrice(String price) {
Price = price;
}
public String getItem_id() {
return item_id;
}
public void setItem_id(String item_id) {
this.item_id = item_id;
}
}
Why it is not working in main activity but work fragment. I am just afraid. and tired...working on the project. so need solution of this problem
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
Add this line to main activity.
My database looks like this
I'm trying to fetch all this data from that USER ID inside Cart. But my RecyclerView shows nothing. After checking, the adapter.getItemCount() returns 0. Where did I wrong? This is my code :
onStart()
private void loadData(){
auth = FirebaseAuth.getInstance().getCurrentUser();
userID = auth.getUid();
final DatabaseReference cartList = FirebaseDatabase.getInstance().getReference().child("Cart");
FirebaseRecyclerOptions<Cart> options =
new FirebaseRecyclerOptions.Builder<Cart>()
.setQuery(cartList.child(userID),Cart.class).build();
FirebaseRecyclerAdapter<Cart,CartHolder> adapter
= new FirebaseRecyclerAdapter<Cart, CartHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull CartHolder holder, int position, #NonNull Cart model) {
holder.txtGia.setText(model.getTotal());
}
#NonNull
#Override
public CartHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cart_item,parent,false);
CartHolder holder = new CartHolder(view);
return holder;
}
};
recyclerView.setAdapter(adapter);
adapter.startListening();
}
Model
public class Cart {
public String pID,num,time,addr,total,userID;
public Cart(){}
public Cart(String num,String pID,String time,String addr,String total,String userID) {
this.num = num;
this.pID = pID;
this.time = time;
this.addr = addr;
this.total = total;
this.userID = userID;
}
public String getNum() {
return num;
}
public String getpID() {
return pID;
}
public String getTime() {
return time;
}
public String getAddr() {
return addr;
}
public String getTotal() {
return total;
}
public String getUserID() {
return userID;
}
}
and ViewHolder
public class CartHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public ImageView shibaImg;
public TextView txtTen,txtMota,txtGia,txtThoigian;
ItemClickListener listener;
public CartHolder(#NonNull View itemView) {
super(itemView);
shibaImg = (ImageView) itemView.findViewById(R.id.cart_item_img);
txtTen = (TextView) itemView.findViewById(R.id.cart_item_ten);
txtMota = (TextView) itemView.findViewById(R.id.cart_item_mota);
txtGia = (TextView) itemView.findViewById(R.id.cart_item_gia);
txtThoigian = (TextView) itemView.findViewById(R.id.cart_item_history);
}
public void setItemClickListener(ItemClickListener listener){
this.listener = listener;
}
#Override
public void onClick(View v) {
listener.onClick(v, getAdapterPosition(),false);
}
}
This code seems to be the problem:
cartList.orderByChild("userID").equalTo(userID)
This code takes every child nodes directly under cartList and orders them on their userID property. But there is no userID property in your screenshot, so this results in an empty list.
My best guess is that the key of each node under cartList is the user ID, in which case you can instead use:
cartList.child(userID)
So:
final DatabaseReference cartList = FirebaseDatabase.getInstance().getReference().child("Cart");
FirebaseRecyclerOptions<Cart> options =
new FirebaseRecyclerOptions.Builder<Cart>()
.setQuery(cartList.child(userID),Cart.class).build();
I've finally figured it out.
For some reason, RecyclerView on my CartActivity needs time to load data in (Maybe cause I have 3 RecyclerView on HomeActivity and sometimes data show up and sometimes It don't, usually 1 or 2 / 3 RecyclerViews show data). When I reload (press back and Start Activity again), RecyclerView will appear and show data.
I am trying to get the details of the Recipe from which Recipe I have clicked in recycler view. I am using this to go to an edit/delete feature. Here is the code for my main activity.
The details that I am trying to get is getting the Name, Ingredients and method.
public class MainActivity extends AppCompatActivity implements RecipeListAdapter.OnItemClickListener {
private RecipeViewModel mRecipeViewModel;
public static final int NEW_WORD_ACTIVITY_REQUEST_CODE = 1;
public String Name;
public String Ingredients;
public String Method;
private RecipeListAdapter mAdapter;
private RecipeDao recDao;
private LiveData<List<Recipe>> RecipeList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = findViewById(R.id.recyclerview);
final RecipeListAdapter adapter = new RecipeListAdapter(this);
recyclerView.setAdapter(adapter);
adapter.setOnItemClickListener(MainActivity.this);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecipeViewModel = new ViewModelProvider(this).get(RecipeViewModel.class);
mRecipeViewModel.getAllRecipes().observe(this, new Observer<List<Recipe>>() {
#Override
public void onChanged(#Nullable final List<Recipe> recipes) {
// Update the cached copy of the words in the adapter.
adapter.setWords(recipes);
}
});
void onItemClick(int position) {
//Delete Below test to pass data through
Recipe recipe = new Recipe("Test", "Yeet", "Jim");
// showAlertDialogBox();
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("Edit or Delete...");
alertDialog.setPositiveButton("Edit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent update = new Intent(MainActivity.this, UpdateRecipeActivity.class);
update.putExtra("Name", recipe.getName());
update.putExtra("Ingredients", recipe.getIngredients());
update.putExtra("Method", recipe.getMethod());
startActivity(update);
}
});
alertDialog.setNegativeButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Delete
}
});
alertDialog.show();
}
Here is the Recipe.class if you needed it!
#Entity(tableName = "recipe_table")
public class Recipe {
#PrimaryKey(autoGenerate = true)
#ColumnInfo(name= "recipeId")
private int RecipeId;
private String name;
private String Ingredients;
private String Method;
#Ignore
public Recipe(String name, String Ingredients, String Method) {
this.RecipeId = RecipeId;
this.name = name;
this.Ingredients = Ingredients;
this.Method = Method;
}
public Recipe(String name) {
this.name = name;
}
public void changeText1(String text){
name = text;
}
//Add Image somehow!
public int getRecipeId() {
return RecipeId;
}
public void setRecipeId(int recipeId) {
RecipeId = recipeId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMethod() {
return Method;
}
public void setMethod(String method) {
Method = method;
}
public String getIngredients() {
return Ingredients;
}
public void setIngredients(String ingredients) {
Ingredients = ingredients;
}
}
If you need anymore files, these are the files I have:
- RecipeListAdapter
- RecipeDao
- RecipeRepository
- RecipeRoomDatabase
- RecipeViewModel
Recipe Adapter code
public class RecipeListAdapter extends RecyclerView.Adapter {
private OnItemClickListener mListener;
private List recipeList;
public interface OnItemClickListener{
void onItemClick(int position, Recipe recipe);
}
public void setOnItemClickListener(OnItemClickListener listener){
mListener = listener;
}
class RecipeViewHolder extends RecyclerView.ViewHolder {
private final TextView recipeItemView;
private RecipeViewHolder(View itemView) {
super(itemView);
recipeItemView = itemView.findViewById(R.id.textView);
itemView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (mListener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION){
mListener.onItemClick(position,
recipeList.get(getAdapterPosition()));
}
}
}
});
}
}
private final LayoutInflater mInflater;
private List<Recipe> mRecipes; // Cached copy of words
RecipeListAdapter(Context context) {
mInflater = LayoutInflater.from(context);
this.recipeList = recipeList;
}
#Override
public RecipeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = mInflater.inflate(R.layout.recyclerview_item, parent,
false);
return new RecipeViewHolder(itemView);
}
#Override
public void onBindViewHolder(RecipeViewHolder holder, int position) {
if (mRecipes != null) {
Recipe current = mRecipes.get(position);
holder.recipeItemView.setText(current.getName());
} else {
// Covers the case of data not being ready yet.
holder.recipeItemView.setText("No Recipes");
}
}
void setWords(List<Recipe> recipes){
mRecipes = recipes;
notifyDataSetChanged();
}
// getItemCount() is called many times, and when it is first called,
// mWords has not been updated (means initially, it's null, and we can't
return null).
#Override
public int getItemCount() {
if (mRecipes != null)
return mRecipes.size();
else return 0;
}
public interface OnNoteListener{}
}
Inside the onItemClick there is one more parameter need to add.
void onItemClick(int position, Recipe recipe) {
//Delete selected recipe from recipe list
arrayList.remove(recipe)
}
The onItemClick method will get called from adapter, from there you have to pass the selected receipe. In the adapter you have to use recipeList.get(getAdapterPosition()) to get the clicked receipe and pass this to the interface method, onItemClick along with the position.
So your code will look like this way inside the adapter,
itemClickListener.onItemClick(position,
recipeList.get(getAdapterPosition()))
Just as a note, please ensure instead of List, you need to take ArrayList to perform remove operation.
Basically, what I am trying to do is use a FirebaseRecyclerAdapter and populate the RecyclerView with my custom designed CardView. The code for newer versions has been changed and therefore, I tried implementing it but didn't work.
This is the code I use to write a year ago, which worked fine and populated my RecyclerView:
FirebaseRecyclerAdapter<DataClass,DataViewHolder> FBRA= new FirebaseRecyclerAdapter<DataClass, DataViewHolder>(
DataClass,
R.layout.myCardView,
DataViewHolder.class,
databaseReference
) {
#Override
protected void populateViewHolder(DataViewHolder viewHolder, DataClass model, int position) {
viewHolder.setTitle(model.gettitle());
viewHolder.setDate(model.getDate());
}
};
myRecyclerView.setAdapter(FBRA);
And now we have to use something like this,
but the problem is this code is not populating my recyclerView (What changes do I need to make here to populate my recyclerView with my cardView?)
#Override
protected void onStart() {
super.onStart();
Query query = FirebaseDatabase.getInstance()
.getReference()
.child("Official_Services");
FirebaseRecyclerOptions<ServiceClass> options = new FirebaseRecyclerOptions.Builder<ServiceClass>()
.setQuery(query, ServiceClass.class)
.build();
FirebaseRecyclerAdapter<ServiceClass, ServiceViewHolder> FBRA = new FirebaseRecyclerAdapter<ServiceClass, ServiceViewHolder>(options) {
#NonNull
#Override
public ServiceViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
View view = LayoutInflater.from(HomeActivity.this).inflate(R.layout.service_card, parent, false);
return new ServiceViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull ServiceViewHolder holder, int position, #NonNull ServiceClass model) {
holder.setServiceName(model.getServiceName());
holder.setServiceCaption(model.getServiceCaption());
}
};
mServiceList.setAdapter(FBRA);
}
Here is my ViewHolder class:
public static class ServiceViewHolder extends RecyclerView.ViewHolder {
public ServiceViewHolder(View itemView) {
super(itemView);
View mView = itemView;
}
public void setServiceName(String serviceName) {
TextView sName = itemView.findViewById(R.id.serviceName);
sName.setText(serviceName);
}
public void setServiceCaption(String serviceCaption) {
TextView sCaption = itemView.findViewById(R.id.serviceCap);
sCaption.setText(serviceCaption);
}
}
And this is my Model class of getters and setters:
public class ServiceClass {
private String serviceName;
private String serviceCode;
private String serviceCaption;
private String serviceIconUrl;
public ServiceClass() {
}
public ServiceClass(String serviceName, String serviceCode, String serviceCaption, String serviceIconUrl) {
this.serviceName = serviceName;
this.serviceCode = serviceCode;
this.serviceCaption = serviceCaption;
this.serviceIconUrl = serviceIconUrl;
}
public String getServiceName() {
return serviceName;
}
public String getServiceCode() {
return serviceCode;
}
public String getServiceCaption() {
return serviceCaption;
}
public String getServiceIconUrl() {
return serviceIconUrl;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
public void setServiceCode(String serviceCode) {
this.serviceCode = serviceCode;
}
public void setServiceCaption(String serviceCaption) {
this.serviceCaption = serviceCaption;
}
public void setServiceIconUrl(String serviceIconUrl) {
this.serviceIconUrl = serviceIconUrl;
}
#Override
public String toString() {
return "ServiceClass{" +
"serviceName='" + serviceName + '\'' +
", serviceCode='" + serviceCode + '\'' +
", serviceCaption='" + serviceCaption + '\'' +
", serviceIconUrl='" + serviceIconUrl + '\'' +
'}';
}
}
Now what changes do I need to do?
Here is my entire java file:
public class HomeActivity extends AppCompatActivity {
private RecyclerView mServiceList;
private FirebaseDatabase mDatabase;
private DatabaseReference myRef;
FirebaseRecyclerAdapter<ServiceClass, ServiceViewHolder> FBRA;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
BottomNavigationViewEx bottomNavigationViewEx = findViewById(R.id.navViewBar);
bottomNavigationViewEx.enableAnimation(false);
bottomNavigationViewEx.enableShiftingMode(false);
bottomNavigationViewEx.setTextVisibility(false);
Calligrapher calligrapher = new Calligrapher(this);
calligrapher.setFont(this, "Helvetica.ttf", true);
mServiceList = findViewById(R.id.serviceRV);
mServiceList.setHasFixedSize(true);
mServiceList.setLayoutManager(new LinearLayoutManager(this));
mDatabase = FirebaseDatabase.getInstance();
myRef = mDatabase.getReference().child("Official_Services");
}
#Override
protected void onStart() {
super.onStart();
FBRA.startListening();
Query query = myRef;
FirebaseRecyclerOptions<ServiceClass> options = new FirebaseRecyclerOptions.Builder<ServiceClass>()
.setQuery(query, ServiceClass.class)
.build();
FBRA = new FirebaseRecyclerAdapter<ServiceClass, ServiceViewHolder>(options) {
#NonNull
#Override
public ServiceViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
View view = LayoutInflater.from(HomeActivity.this).inflate(R.layout.service_card, parent, false);
return new ServiceViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull ServiceViewHolder holder, int position, #NonNull ServiceClass model) {
holder.setServiceName(model.getServiceName());
holder.setServiceCaption(model.getServiceCaption());
}
};
mServiceList.setAdapter(FBRA);
}
public static class ServiceViewHolder extends RecyclerView.ViewHolder {
public ServiceViewHolder(View itemView) {
super(itemView);
View mView = itemView;
}
public void setServiceName(String serviceName) {
TextView sName = itemView.findViewById(R.id.serviceName);
sName.setText(serviceName);
}
public void setServiceCaption(String serviceCaption) {
TextView sCaption = itemView.findViewById(R.id.serviceCap);
sCaption.setText(serviceCaption);
}
}
}
In order to be able to display data from the Firebase realtime database you need to start listening for changes and for that you should add the following line of code in the onStart() method:
#Override
protected void onStart() {
super.onStart();
FBRA.startListening();
}
To stop listening foir changes you need add the following line of code in the onStop() method like this:
#Override
protected void onStop() {
super.onStop();
if(FBRA != null) {
FBRA.stopListening();
}
}
Please see my answer from this post where I have explained why you should remove the listener.
P.S. Please also don't forget to make the FBRA a global variable and remove FirebaseRecyclerAdapter<ServiceClass, ServiceViewHolder> from the declaration of the object.
This is more of an advice. If you want to continue using the old method to populate your
recyclerview ie The "populateViewHolder" method instead of the new "onBindViewHolder" method just use this;
implementation 'com.firebaseui:firebase-ui:1.0.1'
instead of upgraded firebase-ui versions
I have one activity which connects with database and all my data is coming, but I want when I click on one Card view to open data from data Card.
I have like on the first-page category and when I click on one I want to get all projects that are in that category.
I'm still learning (on my own) and this is the first problem I can't solve by myself.
Plesa helps me.
I have tried everything I can find online.
public class MainActivity extends AppCompatActivity {
ImageButton imageButton;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference firemRef = db.collection("kategorije");
private FirmeAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpRecyclerView();
}
private void setUpRecyclerView(){
Query query= firemRef.orderBy("logo",Query.Direction.DESCENDING);
FirestoreRecyclerOptions<Firme> options = new
FirestoreRecyclerOptions.Builder<Firme>()
.setQuery(query,Firme.class)
.build();
adapter= new FirmeAdapter(options);
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
public void onClickButton (View view){
Intent intent= new Intent(MainActivity.this,BeautyIzbornik.class);
MainActivity.this.startActivity(intent);
}
}
My ADAPTER
import com.firebase.ui.firestore.FirestoreRecyclerAdapter;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.squareup.picasso.Picasso;
public class FirmeAdapter extends FirestoreRecyclerAdapter<Firme, FirmeAdapter.FirmeHolder> {
/**
* Create a new RecyclerView adapter that listens to a Firestore Query. See {#link
* FirestoreRecyclerOptions} for configuration options.
*
* #param options
*/
public FirmeAdapter(#NonNull FirestoreRecyclerOptions<Firme> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull FirmeHolder holder, int position, #NonNull final Firme model) {
holder.naziv.setText(model.getNaziv());
holder.setLogo(model.getLogo());
}
#NonNull
#Override
public FirmeHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.firme_item,
viewGroup,false);
return new FirmeHolder(v);
}
class FirmeHolder extends RecyclerView.ViewHolder {
ImageButton imageButton;
TextView naziv;
public FirmeHolder(#NonNull final View itemView) {
super(itemView);
naziv = itemView.findViewById(R.id.naziv);
imageButton =itemView.findViewById(R.id.logo);
}
public void setLogo(String logo) {
Picasso.get().load(logo).into(imageButton);
}
}
}
My Activity with my data
public class Firme {
public String logo;
public String naziv;
public String url;
public Firme ( ) {
}
public Firme (String naziv, String logo , String url){
this.logo= logo;
this.naziv= naziv;
this.url = url;
}
public String getLogo() {
return logo;
}
public String getNaziv() {
return naziv;
}
public void setLogo(String logo){
this.logo = logo;
}
public String getUrl(){
return url;
}
public void setUrl(String url){
this.url=url;
}
}
you have to perform a click listener on RecyclerView item :
Since each item has its own data , you should use this data to show the adequate information :
This how to implement a click listener for RecyclerView
In your RecyclerView.Adapter simply create an interface you can use.
private onItemClickListener mItemClickListener;
public void setOnItemClickListener(onItemClickListener mItemClickListener) {
this.mItemClickListener = mItemClickListener;
}
public interface onItemClickListener {
void onItemClickListener(View view, int position, MyData myData);
}
In this case mItemClickListener is a global variable inside your adapter and the two methods go inside your adapter, too.
Then inside your ViewHolder apply a click listener to your itemView with itemView.setOnClickListener(this) (or whatever component you want clicked to retrieve the data)
#Override
public void onClick(View view) {
if (mItemClickListener != null) {
mItemClickListener.onItemClickListener(view, getAdapterPosition(), my_data.get(getAdapterPosition()));
}
}
This will then pass the view that has been clicked, the position of said view and the object that is contained in your list within that position.
So in your Activity, you can then just simply call the interface.
adapter.setOnItemClickListener(new CustomAdapter.onItemItemClickListener() {
#Override
public void onItemClickListener(View view, int position, MyData data) {
//do on item click functionality here
}
});