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.
Related
I am new to android firebase. The question I have is. The first is to distribute the date from an Activity to several fragments. So far I have solved that problem. But I have a requirement to display the data in Firebase database in each Fragment. But the problem is that the application stops after entering the data in firebase.
stdAttn Activity
public class stdAttnDisplay extends AppCompatActivity {
private ViewPager pager;
private TabLayout tabs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_std_attn_display);
pager=(ViewPager) findViewById(R.id.vpager);
tabs=(TabLayout) findViewById(R.id.tablayout1);
tabs.setupWithViewPager(pager);
tabs.setTabGravity(TabLayout.GRAVITY_FILL);
tabs.setTabMode(TabLayout.MODE_SCROLLABLE);
setupViewPager(pager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
//bundle
Bundle bundle =new Bundle();
bundle.putString("DATE","01-05-2023");
IABF_Attnfrag frag_iabf = new IABF_Attnfrag();
DABF_Attnfrag frag_dabf = new DABF_Attnfrag();
CMA_Attnfrag frag_cma = new CMA_Attnfrag();
CHARTERED_Attnfrag frag_chartered = new CHARTERED_Attnfrag();
ENGLISH_Attnfrag frag_english = new ENGLISH_Attnfrag();
AAT1_Attnfrag frag_aat1 = new AAT1_Attnfrag();
AAT2_Attnfrag frag_aat2 = new AAT2_Attnfrag();
AAT3_Attnfrag frag_aat3 = new AAT3_Attnfrag();
frag_iabf.setArguments(bundle);
frag_dabf.setArguments(bundle);
frag_cma.setArguments(bundle);
frag_chartered.setArguments(bundle);
frag_english.setArguments(bundle);
frag_aat1.setArguments(bundle);
frag_aat2.setArguments(bundle);
frag_aat3.setArguments(bundle);
adapter.addFrag(frag_iabf,"IABF");
adapter.addFrag(frag_dabf,"DABF");
adapter.addFrag(frag_cma,"CMA");
adapter.addFrag(frag_chartered,"CHARTERED");
adapter.addFrag(frag_english,"ENGLISH");
adapter.addFrag(frag_aat1,"AAT-i");
adapter.addFrag(frag_aat2,"AAT-ii");
adapter.addFrag(frag_aat3,"AAT-iii");
viewPager.setAdapter(adapter);
}
}
Fragment
public class IABF_Attnfrag extends Fragment {
String dateTxt;
private Bundle bundle;
myadapter adapter;
RecyclerView recViewiabf;
private DatabaseReference propertyRef;
public IABF_Attnfrag() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_i_a_b_f__attnfrag, container, false);
recViewiabf = (RecyclerView) view.findViewById(R.id.recViewiabf);
bundle = this.getArguments();
dateTxt = bundle.getString("DATE");
Log.e("DATE_FRAG_INBOUND",""+dateTxt);
propertyRef = FirebaseDatabase.getInstance()
.getReference()
.child("attendance")
.child("IABF")
.child(dateTxt);
propertyRef.keepSynced(true);
recViewiabf.setLayoutManager(new LinearLayoutManager(getContext()));
FirebaseRecyclerOptions<modelAttn> options =
new FirebaseRecyclerOptions.Builder<modelAttn>()
.setQuery(propertyRef, modelAttn.class)
.build();
adapter = new myadapter(options);
recViewiabf.setAdapter(adapter);
return view;
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
}
Adapter
public class myadapter extends FirebaseRecyclerAdapter<modelAttn,myadapter.myviewholder>
{
public myadapter(#NonNull FirebaseRecyclerOptions<modelAttn> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull myviewholder holder, int position, #NonNull modelAttn model) {
holder.stdFulName.setText(model.getName());
holder.stdidtv.setText(model.getSt_id());
}
#NonNull
#Override
public myviewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.attn_item,parent,false);
return new myviewholder(view);
}
public class myviewholder extends RecyclerView.ViewHolder {
TextView stdFulName, stdidtv;
public myviewholder(#NonNull View itemView) {
super(itemView);
stdidtv = itemView.findViewById(R.id.indextext);
stdFulName = itemView.findViewById(R.id.nametext);
}
}
}
Model Attn
public class modelAttn {
String Name, st_id;
public modelAttn() {
}
public modelAttn(String name, String st_id) {
this.Name = name;
this.st_id = st_id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getSt_id() {
return st_id;
}
public void setSt_id(String st_id) {
this.st_id = st_id;
}
}
FireBase Database Screenshot
Database Screenshot
What I need is to distribute the data from the Activity to the Fragment and then display the relevant data in the RecyclerView using the data in the Firebase database.
If you create a regular adapter then pass it a list of custom objects which you retrieve from firebase. You can make a static list on your MainActivity that can be referenced anywhere including in the fragment.
The Error
'FirebaseRecyclerAdapter(com.firebase.ui.database.FirebaseRecyclerOptions<com.munopa.revise.Files>)'
in 'com.firebase.ui.database.FirebaseRecyclerAdapter' cannot be
applied to '(java.lang.Class<com.munopa.revise.Files>, int,
java.lang.Class<com.munopa.revise.MainActivity.FilesViewHolder>,
com.google.firebase.database.DatabaseReference)'
My Main Activity
public class MainActivity extends AppCompatActivity {
private EditText mSearchField;
private RecyclerView mFileList;
private FloatingActionButton mSearchButton;
private DatabaseReference mFilesDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFilesDatabase = FirebaseDatabase.getInstance().getReference().child("Files");
mSearchField = findViewById(R.id.search_bar_input);
mFileList = findViewById(R.id.file_list);
mSearchButton = findViewById(R.id.btn_search);
mSearchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
firebaseFileSearch();
}
});
}
private void firebaseFileSearch() {
FirebaseRecyclerAdapter<Files, FilesViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Files, FilesViewHolder>(
Files.class,
R.layout.paper_card,
FilesViewHolder.class,
mFilesDatabase
) {
#Override
protected void onBindViewHolder(#NonNull FilesViewHolder holder, int position, #NonNull Files model) {
}
#NonNull
#Override
public FilesViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return null;
}
};
}
public class FilesViewHolder extends RecyclerView.ViewHolder{
View mView;
public FilesViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
}
}
This is your problem (and where you are getting the error):
FirebaseRecyclerAdapter<Files, FilesViewHolder> firebaseRecyclerAdapter =
new FirebaseRecyclerAdapter<Files, FilesViewHolder>(
Files.class,
R.layout.paper_card,
FilesViewHolder.class,
mFilesDatabase
)
You are calling the constructor of FirebaseRecyclerAdapter with 4 parameters, but it only expects 1 parameter of type FirebaseRecyclerOptions<Files>.
Refer to https://github.com/firebase/FirebaseUI-Android/blob/master/database/README.md for more details about how to set this up.
I am trying to insert info about movie but I am getting this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void kawi15.myapplication.database.DatabaseViewModel.addWatchlistMovie(info.movito.themoviedbapi.model.MovieDb)' on a null object reference
I am sure that Movie is not null because I have Toast which showing me info about this movie.
I find that I need initializate DatabaseViewModel in my OnCreate():
databaseViewModel = new ViewModelProvider(this).get(DatabaseViewModel.class);
but I tried this in OnCreate and OnCreateView and in both its error with 'this':
new ViewModelProvider(this)
I try to put there getContext() or some other stuff but nothing worked here.
This is my Entity class:
#Entity
public class Watchlist {
#PrimaryKey
#ColumnInfo(name = "id")
private int movieId;
#ColumnInfo(name = "movie_title")
private String movieTitle;
#ColumnInfo(name = "poster_path")
private String posterPath;
#ColumnInfo(name = "overview")
private String overview;
#ColumnInfo(name = "release_date")
private String releaseDate;
and getters and setters for all
My Dao class:
#Dao
public interface WatchlistDao {
#Query("SELECT * FROM watchlist ORDER BY movie_title ASC")
List<Watchlist> getAll();
#Insert
void addMovie(Watchlist watchlistMovie);
}
ViewModel class:
public class DatabaseViewModel extends AndroidViewModel {
private AppDatabase db;
public DatabaseViewModel(#NonNull Application application) {
super(application);
db = AppDatabase.getDatabase(application);
}
public void addWatchlistMovie(MovieDb movieDb){
Watchlist addedMovie = new Watchlist();
addedMovie.setMovieId(movieDb.getId());
addedMovie.setMovieTitle(movieDb.getOriginalTitle());
addedMovie.setOverview(movieDb.getOverview());
addedMovie.setPosterPath(movieDb.getPosterPath());
addedMovie.setReleaseDate(movieDb.getReleaseDate());
db.watchlistDao().addMovie(addedMovie);
}
My Fragment class where I am clicking on Movie from list that I want to insert to database:
public class FragmentOne extends Fragment /*implements CustomAdapter.ListItemClickListener*/{
private static RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private DatabaseViewModel databaseViewModel;
private static RecyclerView recyclerView;
private List<MovieDb> data;
//private CustomAdapter.ListItemClickListener mOnClickListener;
public static FragmentOne newInstance() {
FragmentOne fragment = new FragmentOne();
return fragment;
}
/*#Override
public void onListItemClick(int position) {
Toast.makeText(getContext(), data.get(position).getOriginalTitle(), LENGTH_SHORT).show();
}*/
public class MovieTask extends AsyncTask<Void, Void, List<MovieDb>> {
#Override
protected List<MovieDb> doInBackground(Void... voids) {
MovieResultsPage movies = new TmdbApi("f753872c7aa5c000e0f46a4ea6fc49b2").getMovies().getUpcoming("en-US", 1, "US");
List<MovieDb> listMovies = movies.getResults();
return listMovies;
}
#Override
protected void onPostExecute(List<MovieDb> movieDb) {
data = movieDb;
adapter = new CustomAdapter(data);
((CustomAdapter) adapter).setOnMovieDbClicked(movieDb2 -> {
Toast.makeText(getActivity(), movieDb2.getReleaseDate(), LENGTH_SHORT).show();
databaseViewModel.addWatchlistMovie(movieDb2);
});
recyclerView.setAdapter(adapter);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View returnView = inflater.inflate(R.layout.fragment_one, container, false);
recyclerView = (RecyclerView) returnView.findViewById(R.id.my_recycler_view);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getContext()); // ???
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
MovieTask mt = new MovieTask();
mt.execute();
return returnView;
}
}
and my adapter class, maybe not neccessary:
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder>{
private List<MovieDb> dataSet;
private OnMovieDbClicked onMovieDbClicked;
public void setOnMovieDbClicked(OnMovieDbClicked onMovieDbClicked) {
this.onMovieDbClicked = onMovieDbClicked;
}
//final private ListItemClickListener mOnClickListener;
public class MyViewHolder extends RecyclerView.ViewHolder /*implements View.OnClickListener*/{
TextView textViewName;
TextView textViewVersion;
ImageView imageViewIcon;
//private ListItemClickListener mOnClickListener;
public MyViewHolder(View itemView) {
super(itemView);
this.textViewName = (TextView) itemView.findViewById(R.id.text1);
this.textViewVersion = (TextView) itemView.findViewById(R.id.text2);
this.imageViewIcon = (ImageView) itemView.findViewById(R.id.imageView);
itemView.setOnClickListener(view -> {
int pos = getAdapterPosition();
if (onMovieDbClicked != null && pos != RecyclerView.NO_POSITION) {
MovieDb movieDb = dataSet.get(pos);
onMovieDbClicked.movieDbClicked(movieDb);
}
});
//itemView.setOnClickListener(this);
//itemView.setOnClickListener(CustomAdapter.myOnClickListener);
}
/*#Override
public void onClick(View v) {
int position = getAdapterPosition();
mOnClickListener.onListItemClick(position);
}*/
}
public CustomAdapter(List<MovieDb> data /*ListItemClickListener mOnClickListener*/) {
this.dataSet = data;
//this.mOnClickListener = mOnClickListener;
}
public interface OnMovieDbClicked {
void movieDbClicked(MovieDb movieDb);
}
/*public interface ListItemClickListener{
void onListItemClick(int position);
}*/
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.cards_layout, parent, false);
//view.setOnClickListener(FragmentOne.myOnClickListener);
MyViewHolder myViewHolder = new MyViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int listPosition) {
TextView textViewName = holder.textViewName;
TextView textViewVersion = holder.textViewVersion;
ImageView imageView = holder.imageViewIcon;
Glide.with(imageView).load("https://image.tmdb.org/t/p/w500" + dataSet.get(listPosition).getPosterPath()).into(imageView);
textViewName.setText(dataSet.get(listPosition).getOriginalTitle());
textViewVersion.setText(dataSet.get(listPosition).getReleaseDate());
}
#Override
public int getItemCount() {
if(dataSet == null){
return 0;
}
return dataSet.size();
}
}
You have not initialized your databaseViewModel anywhere so the NPE is expected. Make sure to fill the field before accessing it in MovieTask
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.
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