I wanted to fetch some documents in a collection. The document should fetch name and specialty from a document. But each time I run the app, the documents are fetched and shown in the recyclerView as a list (just like in WhatsApp messenger), but the fields are not showing in by TextViews. That is the RecyclerView view display blank lists of `CardView with no texts ( ie the name and specialty I wanted it to display)
Below is the code for the Model, Adapter, and Activity:
THE MODEL
public class Doctor {
private String name;
private String DoctorImageURL;
private String specialty;
public Doctor() {
//empty constructor needed
}
public Doctor(String name, String specialty) {
this.name = name;
this.specialty = specialty;
}
public String getmDoctorName() {
return name;
}
public String getmDoctorSpecialty() {
return specialty;
}
THE ADAPTER
public class DoctorAdapter extends FirestoreRecyclerAdapter<Doctor, DoctorAdapter.DoctorHolder> {
public DoctorAdapter(#NonNull FirestoreRecyclerOptions<Doctor> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull DoctorHolder doctorHolder, int i, #NonNull Doctor doctor) {
doctorHolder.Name.setText(doctor.getmDoctorName());
doctorHolder.Specialty.setText(doctor.getmDoctorSpecialty());
//doctorHolder.DocImage.setImageResource(unifiedModel.getmDoctorImageURL());
//Load images here
}
#NonNull
#Override
public DoctorHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.doctor_list_view_items,
parent, false);
return new DoctorHolder(view);
}
class DoctorHolder extends RecyclerView.ViewHolder{
TextView Name, Specialty;
ImageView DocImage;
public DoctorHolder(#NonNull View itemView) {
super(itemView);
Name = itemView.findViewById(R.id.doctor_name);
Specialty = itemView.findViewById(R.id.doctor_specialty);
DocImage = itemView.findViewById(R.id.doctor_image);
}
}
THE ACTIVITY
public class DoctorActivity extends AppCompatActivity {
FirebaseAuth firebaseAuth;
private FirebaseFirestore rootReference = FirebaseFirestore.getInstance();
private CollectionReference doctorRef = rootReference.collection("doctor");
private DoctorAdapter doctorAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_doctor);
firebaseAuth = FirebaseAuth.getInstance();
setUpRecyclerView();
}
private void setUpRecyclerView() {
// Query FireStore and order items by name in Ascending order
Query query = doctorRef.orderBy("name", Query.Direction.ASCENDING);
FirestoreRecyclerOptions<Doctor> options = new FirestoreRecyclerOptions.Builder<Doctor>()
.setQuery(query, Doctor.class)
.build();
doctorAdapter = new DoctorAdapter(options);
RecyclerView recyclerView = findViewById(R.id.doctor_recycler_view);
recyclerView.setHasFixedSize(true); // For performance reasons
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(doctorAdapter);
}
#Override
protected void onStart() {
super.onStart();
doctorAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
doctorAdapter.stopListening();
}
}
this is the result:
Picture of my database structure
The problem in your code lies in the fact that you have wrong names for your getters in your Doctor class. You have defined the following fields:
private String name;
private String specialty;
With the corresponding getters:
public String getmDoctorName() {
return name;
}
public String getmDoctorSpecialty() {
return specialty;
}
Which is not correct. You getters should be named exactly as your fields. Please see the correct naming:
public String getName() {
return name;
}
public String getrSpecialty() {
return specialty;
}
Regarding the last one:
private String DoctorImageURL;
There is no value in your database. Besides that, your property starts with a capital letter which might lead to some other issues like:
Images not loading from URL by Picasso from Firebase Database
Or
Firebase Android ListView not being displayed
Related
MainActivity
public class MainActivity extends AppCompatActivity {
RecyclerView mRecyclerView;
FirebaseAdapter mAdapter;
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView)findViewById(R.id.recyclerview);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
FirebaseRecyclerOptions<DataClass> options = new FirebaseRecyclerOptions.Builder<DataClass>()
.setQuery(FirebaseDatabase.getInstance().getReference().child("Users"), DataClass.class)
.build();
mAdapter = new FirebaseAdapter(options);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
}
#Override
protected void onStart() {
super.onStart();
mAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
mAdapter.stopListening();
}
}
Adapter
public class FirebaseAdapter extends FirebaseRecyclerAdapter<DataClass,FirebaseAdapter.MyviewHolder> {
private static final String TAG = "FirebaseAdapter";
public FirebaseAdapter(#NonNull FirebaseRecyclerOptions<DataClass> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull MyviewHolder holder, int position, #NonNull DataClass model) {
holder.name.setText(model.getName());
holder.Nickname.setText(model.getNickname());
Log.d(TAG, "onBindViewHolder: Now Bind method executing");
}
#NonNull
#Override
public MyviewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View v= layoutInflater.inflate(R.layout.row_represent,parent,false);
MyviewHolder v1 = new MyviewHolder(v);
Log.d(TAG, "onCreateViewHolder: Now on create method executing");
return v1;
}
public static class MyviewHolder extends RecyclerView.ViewHolder{
TextView name;
TextView Nickname;
public MyviewHolder(#NonNull View itemView) {
super(itemView);
name = (TextView)itemView.findViewById(R.id.names);
Nickname = (TextView) itemView.findViewById(R.id.nick);
}
}
}
Class
public class DataClass {
String name;
String Nickname;
public DataClass(){
}
public DataClass(String name, String Nickname) {
this.name = name;
this.Nickname= Nickname;
}
public String getName() {
return name;
}
public String getNickname() {
return Nickname;
}
}
errors:
2020-11-24 14:19:05.520 7304-7304/com.example.firebasesearchrec D/FirebaseAdapter: onCreateViewHolder: Now on create method executing
2020-11-24 14:19:05.535 7304-7304/com.example.firebasesearchrec D/AndroidRuntime: Shutting down VM
2020-11-24 14:19:05.547 7304-7304/com.example.firebasesearchrec E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.firebasesearchrec, PID: 7304
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.example.firebasesearchrec.DataClass
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean(CustomClassMapper.java:436)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(CustomClassMapper.java:232)
I'm getting Database exception Can't convert object of type java.lang can somebody help me in this issue..................................................
Thank you.................................................................................................................................................
Problem is the result of your query to db returns String. Either you try to read child data of that node or data is not matching the object DataClass
Try debugging the firebase response as I suspect your data type is different, which should be a string
You are trying to read the data of type String which is actually is type of DataClass this is because you are getting this error. You need to change your code as per your requirements.
For more details you can check this link.
I am trying to retrieve data from firebase but my app is keep crashing. i have tried many solution but nothing is working.
In my app i am trying to retrieve name,image,descriptions,price form my Firebase database.
I have written this flowing code to display data in Card view.
my code:-
Main Activity
public class MainActivity extends AppCompatActivity {
private DatabaseReference ProductsRef;
private RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ProductsRef = FirebaseDatabase.getInstance().getReference().child("Products");
recyclerView = findViewById(R.id.recycler_menu);
recyclerView.setHasFixedSize(true);
layoutManager= new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
FirebaseRecyclerOptions<Products> options =
new FirebaseRecyclerOptions.Builder<Products>()
.setQuery(ProductsRef, Products.class)
.build();
FirebaseRecyclerAdapter<Products, ProductViewHolder> adapter =
new FirebaseRecyclerAdapter<Products, ProductViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull ProductViewHolder holder, int position, #NonNull Products model) {
holder.textProductName.setText(model.getName());
holder.textProductDescription.setText(model.getDescription());
holder.textProductPrice.setText("Price = ₹"+model.getPrice());
Picasso.get().load(model.getImage()).into(holder.imageView);
}
#NonNull
#Override
public ProductViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.product_items_layout, parent,false);
ProductViewHolder holder = new ProductViewHolder(view);
return holder;
}
};
recyclerView.setAdapter(adapter);
adapter.startListening();
}
}
Products Activity
public class Products {
private String description, image,name,price ;
public Products() {
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
ProductViewHolder Activity
[enter image description here][1]public class ProductViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView textProductName, textProductDescription, textProductPrice;
public ImageView imageView;
public ProductViewHolder(#NonNull View itemView) {
super(itemView);
imageView= imageView.findViewById(R.id.product_image);
textProductName = textProductName.findViewById(R.id.product_name);
textProductDescription = textProductDescription.findViewById(R.id.product_description);
textProductPrice = textProductPrice.findViewById(R.id.product_price);
}
#Override
public void onClick(View v) {
}
}
It seems that your assignments at ProductViewHolder are wrong, try this:
public ProductViewHolder(#NonNull View itemView) {
super(itemView);
imageView= itemView.findViewById(R.id.product_image);
textProductName = itemView.findViewById(R.id.product_name);
textProductDescription = itemView.findViewById(R.id.product_description);
textProductPrice = itemView.findViewById(R.id.product_price);}
Hope I helped!
Attempt to invoke virtual method 'android.view.View
android.widget.ImageView.findViewById(int)' on a null object reference
findViewById() is nullable, so it might return a null value.. make sure that the ImageView resource id product_name exists in your R.layout.product_items_layout layout and not in any other layouts in your project.
I'm trying to create a code saying "Where the username that is logged in matches the username of a created recipe, only show these database entries in the recyclerview on my MyRecipes.java activity". I'm having trouble working out where to put this potential statement. Looking at my code, where would you put that statement, if or otherwise?
The userLoggedIn and loggedUser is the variable for the currently logged in user.
The thisUser is what I've set as the users pulled from the database when the recyclerview is populating in the recyclerview.java class.
Any help would be greatly appreciated!
RecyclerView.java class
private static String thisUser;
String userLoggedIn = HomeActivity.getUserLogged();
private Context mContext;
private RecipesAdapter mRecipeAdapter;
public void setConfig (RecyclerView recyclerView, Context context, List<Recipes> recipes, List<String> keys){
mContext = context;
mRecipeAdapter = new RecipesAdapter(recipes, keys);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
recyclerView.setAdapter(mRecipeAdapter);
}
class RecipeItemView extends RecyclerView.ViewHolder{
private TextView mTitle;
private TextView mIngredients;
private TextView mMethod;
private TextView mUser;
private String key;
public RecipeItemView(ViewGroup parent){
super(LayoutInflater.from(mContext).inflate(R.layout.recipe_list_item, parent,false));
mTitle = (TextView) itemView.findViewById(R.id.tvTitle);
mMethod = (TextView) itemView.findViewById(R.id.tvMethod);
mIngredients = (TextView) itemView.findViewById(R.id.tvIngredients);
mUser = (TextView) itemView.findViewById(R.id.tvUser);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, RecipeDetails.class);
intent.putExtra("key", key);
intent.putExtra("title", mTitle.getText().toString());
intent.putExtra("ingredients", mIngredients.getText().toString());
intent.putExtra("method", mMethod.getText().toString());
mContext.startActivity(intent);
}
});
}
public void bind(Recipes recipes, String key) {
mTitle.setText(recipes.getTitle());
mIngredients.setText(recipes.getIngredients());
mMethod.setText(recipes.getMethod());
mUser.setText(recipes.getCreatedUser());
thisUser = mUser.getText().toString().trim();
this.key = key;
}
}
public static String getUserLoggedIn(){
return thisUser;
}
class RecipesAdapter extends RecyclerView.Adapter<RecipeItemView> {
private List<Recipes> mRecipeList;
private List<String> mKeys;
public RecipesAdapter(List<Recipes> mRecipeList, List<String> mKeys) {
this.mRecipeList = mRecipeList;
this.mKeys = mKeys;
}
#NonNull
#Override
public RecipeItemView onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new RecipeItemView(parent);
}
#Override
public void onBindViewHolder(#NonNull RecipeItemView holder, int position) {
holder.bind(mRecipeList.get(position), mKeys.get(position));
}
#Override
public int getItemCount() {
return mRecipeList.size();
}
}
}
MyRecipes.java (Where the recycler view populates and shows all the recipes)
String loggedUser = HomeActivity.getUserLogged();
String thisUser = RecyclerViewConfig.getUserLoggedIn();
Button addRecipes;
private RecyclerView mRecyclerView;
private String passedUsername;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_recipes);
passedUsername = getIntent().getStringExtra("loggedUsername1");
mRecyclerView = (RecyclerView) findViewById(R.id.rvRecipes);
new FirebaseDatabaseHelper().readRecipes(new FirebaseDatabaseHelper.DataStatus() {
#Override
public void DataIsLoaded(List<Recipes> recipes, List<String> keys) {
new RecyclerViewConfig().setConfig(mRecyclerView, MyRecipesActivity.this, recipes, keys);
}
#Override
public void DataIsInserted() {
}
#Override
public void DataIsUpdated() {
}
#Override
public void DataIsDeleted() {
}
});
addRecipes = findViewById(R.id.btnAddNewRecipe);
addRecipes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent addrecipe = new Intent(MyRecipesActivity.this, AddRecipes.class);
addrecipe.putExtra("loggedUsername2", passedUsername);
startActivity(addrecipe);
}
});
}
}
If i understand correctly, you need to show the recipes to the user only if he/she is the one who created it? Assuming that, below change in the code will do the trick.
Change your bind() method as follows.
public void bind(Recipes recipes, String key) {
thisUser = mUser.getText().toString().trim();
if(thisUser.equals(recipes.getCreatedUser)) {
mTitle.setText(recipes.getTitle());
mIngredients.setText(recipes.getIngredients());
mMethod.setText(recipes.getMethod());
mUser.setText(recipes.getCreatedUser());
this.key = key;
}
}
Though that is a naive approach, a better approach would be to filter the recipes list with created user when you load data from Firebase with readRecipes() method itself. To do that a query can be used as below(the exact query below might not work for you depending on your DB structure. Change it as needed)
Query query = reference.child("Recipes").orderByChild("userCreated").equalTo(thisUser);
So i have my a list on my main activity that i want to be able to access in another class. The second class is supposed to add more records to the list based on the users input but i don't know how to access it. Can anybody help?
Contactos.java:
This is my main class and its also where the list is kept, i did a test run on it so that's why the constructor is filled with numbers. I want to be able to add to the list from another class.
public class Contactos extends AppCompatActivity {
private Button btnReciente;
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnReciente = (Button) findViewById(R.id.Reciente);
listView = (ListView) findViewById(R.id.list1);
List<contactosLista> list1 = new ArrayList<contactosLista>();
list1.add(new contactosLista("1","2","3","4","5","6"));
ContactosAdapter adapter = new ContactosAdapter(this,list1);
listView.setAdapter(adapter);
ContactosAdapter.java: This is where i inflate the list, i use it so i can use a .xml file to better display the values in the list.
public class ContactosAdapter extends BaseAdapter
{
private Context mContext;
private List<contactosLista>mListaContactos;
public ContactosAdapter(Context context, List<contactosLista> list)
{
mContext = context;
mListaContactos = list;
}
#Override
public int getCount() {
return mListaContactos.size();
}
#Override
public Object getItem(int position) {
return mListaContactos.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
contactosLista entrada = mListaContactos.get(position);
if(convertView == null)
{
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(R.layout.contactos_row,null);
}
TextView Contact = (TextView) convertView.findViewById(R.id.Contacto);
Contact.setText(entrada.getmName() + " -- " + entrada.getmEmpresa());
return convertView;
}
}
contactosLista.java: This the class that defines the elements that the list needs. i made a constructor that accommodates all the strings and made all the setters & getters
public class contactosLista
{
private String mName;
private String mEmpresa;
private String mRazon;
private String mDireccion;
private String mEstatus;
private String mPaquete;
public contactosLista(String mName, String mEmpresa, String mRazon, String mDireccion, String mEstatus, String mPaquete)
{
this.mName = mName;
this.mEmpresa = mEmpresa;
this.mRazon = mRazon;
this.mDireccion = mDireccion;
this.mEstatus = mEstatus;
this.mPaquete = mPaquete;
}
public String getmName() {
return mName;
}
public void setmName(String mName) {
this.mName = mName;
}
public String getmEmpresa() {
return mEmpresa;
}
public void setmEmpresa(String mEmpresa) {
this.mEmpresa = mEmpresa;
}
public String getmRazon() {
return mRazon;
}
public void setmRazon(String mRazon) {
this.mRazon = mRazon;
}
public String getmDireccion() {
return mDireccion;
}
public void setmDireccion(String mDireccion) {
this.mDireccion = mDireccion;
}
public String getmEstatus() {
return mEstatus;
}
public void setmEstatus(String mEstatus) {
this.mEstatus = mEstatus;
}
public String getmPaquete() {
return mPaquete;
}
public void setmPaquete(String mPaquete) {
this.mPaquete = mPaquete;
}
}
createContact.java: finally this is the class where i want to be able to access the list from Contactos.java, I have a layout file that has a bunch of Edit text so that i can record input from the user. When the user clicks on the button to save i want my void "GuardarCon" to save the input from the user to strings and then i want to use those strings as parameters for my list. This is where the problem arises, i don't know how to call the list. PLS help.
public class createContact extends AppCompatActivity
{
EditText nombre;
EditText empresa;
EditText razon;
EditText direccion;
EditText estatus;
EditText paquete;
String snombre;
String sempresa;
String srazon;
String sdireccion;
String sestatus;
String spaquete;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_contact);
nombre = (EditText) findViewById(R.id.nombreT);
empresa = (EditText) findViewById(R.id.empresaT);
razon = (EditText) findViewById(R.id.razonSocialT);
direccion = (EditText) findViewById(R.id.direccionT);
estatus = (EditText) findViewById(R.id.EstatusT);
paquete = (EditText) findViewById(R.id.paqueteT);
}
public void GuardarCon(View view)
{
snombre = nombre.getText().toString();
sempresa = empresa.getText().toString();
srazon = razon.getText().toString();
sdireccion = direccion.getText().toString();
sestatus = estatus.getText().toString();
spaquete = paquete.getText().toString();
}
Create a singleton class and access and modify data as you want !
public class DataHolder{
public static final DataHolder instance = new DataHolder();
private List<Your_Data_Type> data;
//Your methods goes here...
}
You could use startActivityForResult method to start createContact from Contactos activity and after the addition process is done use setResult method to return the added item to the Contactos activity and handle adding the item to the list in onActivityResult.
take a look at this link for further info:
https://developer.android.com/training/basics/intents/result
When my Home fragment uses regular buttons through intent to go to a new class. On the new class when I try to use RecylerVie and Firebase to show data, the data does not appear and the app crashes.
On my Firebase the nodes go from project --> to DataHome --> Home1.
Home 1 has the attributes description,directions, ingredients, image, title
DataHome also has other nodes named Home2, etc. But in this case I'm only trying to show data from Home1 on this class.
database image
The logcat says Fatal Exception Main: Process: com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.example.tmrecipes.Model.DataHome
This is the class:
public class BeefSamosa extends AppCompatActivity {
FirebaseDatabase mHomeFireBaseDatabase;
RecyclerView myhomeview;
private DatabaseReference DataHomeRef;
private LinearLayoutManager mLinearLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_beef_samosa);
//Back Button
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Beef Samosa");
//Recycler View
myhomeview = findViewById(R.id.beefview);
myhomeview.setHasFixedSize(true);
//set layout as LinearLayout
myhomeview.setLayoutManager(new LinearLayoutManager(this));
//send query to firebase database
mHomeFireBaseDatabase = FirebaseDatabase.getInstance();
DataHomeRef = mHomeFireBaseDatabase.getInstance().getReference("DataHome").child("Home1");
}
#Override
public boolean onOptionsItemSelected (MenuItem item){
int id = item.getItemId();
if(id == android.R.id.home){
//ends the activity
this.finish();
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onStart() {
super.onStart();
Query query = FirebaseDatabase.getInstance()
.getReference("DataHome")
.child("Home1");
FirebaseRecyclerOptions<DataHome> options =
new FirebaseRecyclerOptions.Builder<DataHome>()
.setQuery(DataHomeRef, DataHome.class)
.build();
FirebaseRecyclerAdapter<DataHome,DataHomeViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<DataHome, DataHomeViewHolder>(options) {
#NonNull
#Override
public DataHomeViewHolder onCreateViewHolder(ViewGroup parent, int viewtype) {
final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_home_deatil, parent, false);
return new DataHomeViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull DataHomeViewHolder holder, int position, #NonNull DataHome model) {
holder.setDetails(getApplicationContext(), model.getTitle(), model.getImage(), model.getDescription() , model.getIngredients(), model.getDirections());
}
};
firebaseRecyclerAdapter.startListening();
myhomeview.setAdapter(firebaseRecyclerAdapter);
}
//DataHomeViewHolder class
public static class DataHomeViewHolder extends RecyclerView.ViewHolder {
View mview;
public DataHomeViewHolder(#NonNull View itemView) {
super(itemView);
mview = itemView;
}
public void setDetails(Context ctx, String title, String image, String description, String ingredients , String directions) {
//Views
TextView mHomeTitle = mview.findViewById(R.id.titlewords);
ImageView mHomeImage = mview.findViewById(R.id.loading_pic);
TextView mDescriptionTitle = mview.findViewById(R.id.descriptionwords);
TextView mIngredientsTitle = mview.findViewById(R.id.ingredientwords);
TextView mDirectionsTitle = mview.findViewById(R.id.directionwords);
//Set data to views
mHomeTitle.setText(title);
mDescriptionTitle.setText(description);
mIngredientsTitle.setText(ingredients);
mDirectionsTitle.setText(directions);
Picasso.get().load(image).into(mHomeImage);
}
}
}
My model class is:
public class DataHome {
public String title ,image, description, ingredients, directions;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getIngredients() {
return ingredients;
}
public void setIngredients(String ingredients) {
this.ingredients = ingredients;
}
public String getDirections() {
return directions;
}
public void setDirections(String directions) {
this.directions = directions;
}
public DataHome(String title, String image, String description, String ingredients, String directions){
this.title =title;
this.image = image;
this.description = description;
this.ingredients = ingredients;
this.directions=directions;
}
}
Edit: The changed class is:
public class BeefSamosa extends AppCompatActivity {
private FirebaseRecyclerAdapter firebaseRecyclerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_beef_samosa);
//Back Button
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Beef Samosa");
RecyclerView recyclerView = findViewById(R.id.beef_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child("DataHome");
FirebaseRecyclerOptions<DataHome> firebaseRecyclerOptions = new FirebaseRecyclerOptions.Builder<DataHome>()
.setQuery(query, DataHome.class)
.build();
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<DataHome, DataHomeViewHolder>(firebaseRecyclerOptions) {
#Override
protected void onBindViewHolder(#NonNull DataHomeViewHolder dataHomeViewHolder, int position, #NonNull DataHome dataHome) {
dataHomeViewHolder.setDataHome(dataHome);
}
#Override
public DataHomeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.homedetail, parent, false);
return new DataHomeViewHolder(view);
}
};
recyclerView.setAdapter(firebaseRecyclerAdapter);
}
#Override
protected void onStart() {
super.onStart();
firebaseRecyclerAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
if (firebaseRecyclerAdapter!= null) {
firebaseRecyclerAdapter.stopListening();
}
}
#Override
public boolean onOptionsItemSelected (MenuItem item){
int id = item.getItemId();
if(id == android.R.id.home){
//ends the activity
this.finish();
}
return super.onOptionsItemSelected(item);
}
//DataHomeViewHolder class
private class DataHomeViewHolder extends RecyclerView.ViewHolder {
private TextView imagetoo, titletext, description, ingredients, directions;
DataHomeViewHolder(View itemView){
super(itemView);
imagetoo = itemView.findViewById(R.id.imagetoo);
titletext = itemView.findViewById(R.id.titletext);
description = itemView.findViewById(R.id.description);
ingredients = itemView.findViewById(R.id.ingredients);
directions = itemView.findViewById(R.id.directions);
}
void setDataHome(DataHome DataHome) {
String imageto = DataHome.getImage();
imagetoo.setText(imageto);
String titleto = DataHome.getTitle();
titletext.setText(titleto);
String descriptionto = DataHome.getDescription();
description.setText(descriptionto);
String ingredientsto = DataHome.getIngredients();
ingredients.setText(ingredientsto);
String directionsto = DataHome.getDirections();
directions.setText(directionsto);
}
}
}
You are getting the following error:
Fatal Exception Main: Process: com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.example.tmrecipes.Model.DataHome
Because the children under Home1 node are strings and not DataHome objects. To solve this, you need to pass to your FirebaseRecyclerOptions object a query that points to a node where DataHome objects exist. So please change the following line of code:
Query query = FirebaseDatabase.getInstance()
.getReference("DataHome")
.child("Home1");
to
Query query = FirebaseDatabase.getInstance()
.getReference("DataHome");
See, I have removed the call to .child("Home1") because this is producing the error. This change will help you display all DataHome objects that exist within the all DataHome node.
If you want to display only the details of Home1 for example, there is no need to use the Firebase-UI library, you can simply get the value of all properties and display them in a list as explained in my answer from this post:
How can I retrieve data from Firebase to my adapter