Populating RecyclerView from firebase database - java

I am new to Android developing and trying to display data from Firebase Database to Recyclerview but when I run the application the Users Activity is blank or nothing displayed on my RecyclerView.
I'm stuck and still the output is the same: nothing is displayed.
UsersActivity:
private Toolbar mToolbar;
private RecyclerView mUsersList;
private DatabaseReference mUsersDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_users);
mToolbar = (Toolbar) findViewById(R.id.users_appBar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("Users");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mToolbar.setTitleTextColor(Color.WHITE);
mToolbar.setSubtitleTextColor(Color.WHITE);
mUsersDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
mUsersList = (RecyclerView) findViewById(R.id.users_list);
mUsersList.setHasFixedSize(true);
mUsersList.setLayoutManager(new LinearLayoutManager(this));
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerAdapter<Users, UsersViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Users, UsersViewHolder>(
Users.class,
R.layout.users_single_layout,
UsersViewHolder.class,
mUsersDatabase
) {
#Override
protected void populateViewHolder(UsersViewHolder usersViewHolder, Users users, int i) {
usersViewHolder.setName(users.getName());
}
};
mUsersList.setAdapter(firebaseRecyclerAdapter);
}
public static class UsersViewHolder extends RecyclerView.ViewHolder
{
View mView;
public UsersViewHolder(#NonNull View itemView) {
super(itemView);
mView = itemView;
}
public void setName(String name)
{
TextView userNameView = (TextView) mView.findViewById(R.id.user_name);
userNameView.setText(name);
}
}
and this is my code in my Model class which is Users
private String name;
private String image;
private String status;
public Users()
{
}
public Users(String name, String image, String status) {
this.name = name;
this.image = image;
this.status = status;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}

You are using an old version of FirebaseUI, you need to remove mUsersList.setHasFixedSize(true); for the data to be displayed

Related

Show the latest item firest in Firebase ui Realtime database [duplicate]

I try to use the FirebaseUI-Realtime Database Android lib to simply display a data set in a viepager2 with recycler-view adapter
When I get the data, I got the oldest data first, and i need to show the latest first . So I need a reverse order. How i can do it in RecyclerView adapter?
MainActivity.java
public class MainActivity extends AppCompatActivity {
ViewPager2 viewPager2;
videoadapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
viewPager2 = (ViewPager2) findViewById(R.id.vpager);
FirebaseRecyclerOptions<videomodel> options = new FirebaseRecyclerOptions.Builder<videomodel>()
.setQuery(FirebaseDatabase.getInstance().getReference().child("videos"), videomodel.class).build();
adapter = new videoadapter(options);
viewPager2.setAdapter(adapter);
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
}
videoadapter.java
public class videoadapter extends
FirebaseRecyclerAdapter<videomodel, videoadapter.myviewholder> {
private Context context;
private AppCompatActivity activity;
private Timer _timer = new Timer();
private double positionc;
private TimerTask check;
private ProgressBar progressbar11;
private ViewPager2 viewPager;
public videoadapter(#NonNull FirebaseRecyclerOptions<videomodel> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull myviewholder holder, int position, #NonNull videomodel model) {
holder.setdata(model);
holder.simpleExoPlayer.prepare();
}
#NonNull
#Override
public myviewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_video_row, parent, false);
return new myviewholder(view);
}
#Override
public void onViewAttachedToWindow(videoadapter.myviewholder holder) {
super.onViewAttachedToWindow(holder);
holder.playerView.getPlayer().seekTo(0);
holder.playerView.getPlayer().setPlayWhenReady(true);
holder.playerView.getPlayer().prepare();
}
#Override
public void onViewDetachedFromWindow(videoadapter.myviewholder holder) {
super.onViewDetachedFromWindow(holder);
holder.playerView.getPlayer().setPlayWhenReady(false);
holder.playerView.getPlayer().stop();
}
class myviewholder extends RecyclerView.ViewHolder {
PlayerView playerView;
SimpleExoPlayer simpleExoPlayer;
LinearLayout sec_mid;
ProgressBar progressbar1;
DefaultTrackSelector trackSelector;
ImageView play,pause;
TextView title,desc;
public myviewholder(#NonNull View view) {
super(view);
playerView = (PlayerView) view.findViewById(R.id.statusSliderVideo);
sec_mid = (LinearLayout) view.findViewById(R.id.sec_controlvid1);
progressbar1 = (ProgressBar) view.findViewById(R.id.progressbar11);
play = (ImageView) view.findViewById(R.id.exo_play);
pause = (ImageView) view.findViewById(R.id.exo_pause);
title = (TextView) view.findViewById(R.id.textVideoTitle);
desc = (TextView) view.findViewById(R.id.textVideoDescription);
}
void setdata(videomodel obj) {
progressbar1.getProgressDrawable().setColorFilter(Color.WHITE, android.graphics.PorterDuff.Mode.SRC_IN);
progressbar1.setIndeterminate(true);
title.setText(obj.getTitle());
desc.setText(obj.getDesc());
// get data
Uri videoUri = Uri.parse(obj.getUrl());
simpleExoPlayer = new SimpleExoPlayer.Builder(playerView.getContext()).build();
playerView.setPlayer(simpleExoPlayer);
playerView.setKeepScreenOn(true);
MediaItem mediaItem = MediaItem.fromUri(videoUri);
simpleExoPlayer.setMediaItem(mediaItem);
simpleExoPlayer.prepare();
playerView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View _view) {
if (simpleExoPlayer.isPlaying()) {
simpleExoPlayer.pause();
} else {
simpleExoPlayer.play();
}
}
});
simpleExoPlayer.addListener(new Player.Listener() {
#Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
if (playbackState == Player.STATE_BUFFERING) {
progressbar1.setIndeterminate(true);
} else {
progressbar1.setIndeterminate(false);
}
if (playbackState == Player.STATE_ENDED) {
simpleExoPlayer.seekTo(0);
simpleExoPlayer.setPlayWhenReady(true);
}
}
});
Activity activity = new Activity();
check = new TimerTask() {
#Override
public void run() {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
progressbar1.setMax((int) simpleExoPlayer.getDuration());
progressbar1.setProgress((int) simpleExoPlayer.getCurrentPosition());
}
});
}
};
_timer.scheduleAtFixedRate(check, (int) (0), (int) (1));
}
}
}
videomodel
public class videomodel {
String desc,title,url;
public videomodel(String desc, String title, String url) {
this.desc = desc;
this.title = title;
this.url = url;
}
videomodel()
{
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}

I want to display User data from Firebase to RecyclerView

I want to retrieve data from Firebase to recyclerView through FirebaseRecyclerOptionsbut it keeps showing blanks pages,I want to display the registered Users in my App and there details in a layout,I have no idea where I have gone wrong,I have multi check on my codes and I can't see any error Please can Anyone help me here.
Here Are Code for ListAdapter,Model and ListActivity
public class ListActivity extends AppCompatActivity {
private FirebaseAuth firebaseAuth;
private DatabaseReference reference;
RecyclerView recyclerView;
ListAdapter listAdapter;
private String CurrentUserID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
recyclerView = findViewById(R.id.children_home_list);
firebaseAuth = FirebaseAuth.getInstance();
CurrentUserID = firebaseAuth.getCurrentUser().getUid();
reference = FirebaseDatabase.getInstance().getReference().child("Children Home Details");
recyclerView.setLayoutManager(new LinearLayoutManager(this));
FirebaseRecyclerOptions<Model> options =
new FirebaseRecyclerOptions.Builder<Model>()
.setQuery(reference, Model.class)
.build();
listAdapter = new ListAdapter(options);
}
#Override
protected void onStart() {
super.onStart();
listAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
listAdapter.stopListening();
}
public class ListAdapter extends FirebaseRecyclerAdapter<Model,ListAdapter.ListViewHolder> {
public ListAdapter(#NonNull FirebaseRecyclerOptions<Model> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull ListViewHolder holder, int position, #NonNull Model model) {
holder.Name.setText(model.getName());
holder.Phone.setText(model.getPhone());
holder.Location.setText(model.getLocation());
holder.Email.setText(model.getMailAddress());
//Glide.with(holder.circleImageView.getContext()).load(model.IMAGELINK()).into(holder.circleImageView);
}
#NonNull
#Override
public ListViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.singlerow,parent,false);
return new ListViewHolder(view);
}
class ListViewHolder extends RecyclerView.ViewHolder {
CircleImageView circleImageView;
TextView Name,Phone,Email,Location;
public ListViewHolder(#NonNull View itemView) {
super(itemView);
circleImageView = itemView.findViewById(R.id.img1);
Name = itemView.findViewById(R.id.HomeName);
Phone = itemView.findViewById(R.id.phoneName);
Email = itemView.findViewById(R.id.paypalAddress);
Location = itemView.findViewById(R.id.location);
}
}
}
public class Model {
String Name,Phone,Location,MailAddress;
public Model(String name, String phone, String location, String mailAddress) {
Name = name;
Phone = phone;
Location = location;
MailAddress = mailAddress;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getPhone() {
return Phone;
}
public void setPhone(String phone) {
Phone = phone;
}
public String getLocation() {
return Location;
}
public void setLocation(String location) {
Location = location;
}
public String getMailAddress() {
return MailAddress;
}
public void setMailAddress(String mailAddress) {
MailAddress = mailAddress;
}
}

How to fix incompatible types: fragment cannot be converted to Context

i am trying to view items from my database and i have written everything to retrieve that and display it in an activity page. but this one line of code gives an error that doesn't allow the app to run:
here is my detailed code:
public class HomeFragment extends Fragment {
private String name;
private String location;
private String country;
private String address;
public HomeFragment() {
}
public HomeFragment(String name, String location, String country, String address) {
this.name = name;
this.location = location;
this.country = country;
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
private FirebaseFirestore firebaseFirestore;
private RecyclerView FirestoreList;
private FirestoreRecyclerAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
firebaseFirestore = FirebaseFirestore.getInstance();
FirestoreList = FirestoreList.findViewById(R.id.firestore_list);
//query
Query q = firebaseFirestore.collection("Shops");
//recycle options
FirestoreRecyclerOptions<ShopModel> options = new FirestoreRecyclerOptions.Builder<ShopModel>().setQuery(q, ShopModel.class).build();
adapter = new FirestoreRecyclerAdapter<ShopModel, ShopViewHolder>(options) {
#NonNull
#Override
public ShopViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_home,parent,false);
return new ShopViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull ShopViewHolder holder, int position, #NonNull ShopModel model) {
holder.list_name.setText(model.getName());
holder.list_country.setText(model.getName());
holder.list_location.setText(model.getName());
holder.list_address.setText(model.getName());
}
};
FirestoreList.setHasFixedSize(true);
FirestoreList.setLayoutManager(new LinearLayoutManager(this));// this is the line that is giving me the error
FirestoreList.setAdapter(adapter);
return inflater.inflate(R.layout.fragment_home, container, false);
}
private class ShopViewHolder extends RecyclerView.ViewHolder {
private TextView list_name;
private TextView list_country;
private TextView list_location;
private TextView list_address;
public ShopViewHolder(#NonNull View itemView) {
super(itemView);
list_name = itemView.findViewById(R.id.list_name);
list_country = itemView.findViewById(R.id.list_country);
list_location = itemView.findViewById(R.id.list_location);
list_address = itemView.findViewById(R.id.list_address);
}
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
}
this is the line where there is a problem at
FirestoreList.setLayoutManager(new LinearLayoutManager(this));// this is the line that is giving me the error
what can i do to resolve this?
You are passing your fragment to LinearLayoutManager, not the Context
So what you need to do is simply replace this line
FirestoreList.setLayoutManager(new LinearLayoutManager(this));
To
FirestoreList.setLayoutManager(new LinearLayoutManager(requireContext()));
Can you please make an object for FirestoreList and try to set the LayoutManager to the object ?
FirestoreList fsList = FirestoreList.findViewById(R.id.firestore_list);
...
fsList.setLayoutManager(new LinearLayoutManager(this));
Change this statement :
return inflater.inflate(R.layout.fragment_home, container, false);
to:
View view = inflater.inflate(R.layout.fragment_home, container, false);

FIrebase Adapter not populating data correctly

Sorry if i m asking lame questions i m new to android development.
I have a activity in which i m populating firebase recycler adapter problem is that it is not populating recycler (loadFoodlist) when i click on that activity once.
But when i click that activity twice or thrice after that it is getting data perfectly fine i don't know what is the problem it happens whenever i relaunch the app?
Database structure
database image
public class FoodDetailModel {
String name, price, description, type;
public FoodDetailModel(){
}
public FoodDetailModel(String name, String price, String description, String type) {
this.name = name;
this.price = price;
this.description = description;
this.type = type;
}
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;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
public class FoodDetailViewHolder extends RecyclerView.ViewHolder {
public TextView foodname,price,description;
public Button delete;
public ImageView type;
public FoodDetailViewHolder(#NonNull View itemView) {
super(itemView);
foodname = (TextView) itemView.findViewById(R.id.food_name);
price = (TextView) itemView.findViewById(R.id.food_price);
description = (TextView) itemView.findViewById(R.id.food_description);
delete = (Button) itemView.findViewById(R.id.add_to_cart);
type = itemView.findViewById(R.id.type);
}
}
public class FoodDetail extends AppCompatActivity {
FirebaseDatabase database;
FirebaseAuth mAuth;
DatabaseReference ref;
FirebaseRecyclerAdapter<FoodDetailModel, FoodDetailViewHolder> adapter;
RecyclerView recycler_menu;
RecyclerView.LayoutManager layoutManager;
CollapsingToolbarLayout collapsingToolbarLayout;
ProgressDialog dialog1 ;
String resID = "", resName = "";
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food_detail);
dialog1 = new ProgressDialog(FoodDetail.this);
mAuth = FirebaseAuth.getInstance();
imageView = (ImageView) findViewById(R.id.food_img);
if(getIntent() != null){
resID = getIntent().getStringExtra("restraunt_id");
resName = getIntent().getStringExtra("name");
}
// init firebase
collapsingToolbarLayout = findViewById(R.id.collapsing);
collapsingToolbarLayout.setExpandedTitleTextAppearance(R.style.ExpandedAppBar);
collapsingToolbarLayout.setCollapsedTitleTextAppearance(R.style.CollapsedAppBar);
collapsingToolbarLayout.setTitle(resName);
// load restuarant list from firebase
recycler_menu = (RecyclerView) findViewById(R.id.foodmenu_list);
recycler_menu.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recycler_menu.setLayoutManager(layoutManager);
loadFoodList();
loadName();
}
private void loadName() {
DatabaseReference ref1 = FirebaseDatabase.getInstance().getReference();
DatabaseReference mostafa = ref1.child("restaurant").child(resID).child("img");
mostafa.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String imgURL = dataSnapshot.getValue(String.class);
Picasso.with(getBaseContext()).load(imgURL).fit().into(imageView);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void loadFoodList() {
ref = FirebaseDatabase.getInstance().getReference().child("menu").child(resID);
System.out.println("getttts here" + ref.toString());
adapter = new FirebaseRecyclerAdapter<FoodDetailModel, FoodDetailViewHolder>
(FoodDetailModel.class,R.layout.food_detail_blueprint, FoodDetailViewHolder.class,ref) {
#Override
protected void populateViewHolder(final FoodDetailViewHolder viewHolder, final FoodDetailModel model, final int position) {
final String x = adapter.getRef(position).toString();
viewHolder.foodname.setText(model.getName());
viewHolder.price.setText("₹"+model.getPrice());
viewHolder.description.setText(model.getDescription());
String typ = model.getType();
if (typ.equals("veg")){
viewHolder.type.setImageResource(R.drawable.veg);
} else {
viewHolder.type.setImageResource(R.drawable.nonveg);
}
viewHolder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder alert = new AlertDialog.Builder(FoodDetail.this);
alert.setTitle("Delete entry");
alert.setMessage("Are you sure you want to delete?");
alert.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alert.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// close dialog
dialog.cancel();
}
});
alert.show();
}
});
}
};
recycler_menu.setAdapter(adapter);
}
}

Firebase database RecyclerView in a fragment causing Error in converting database to String

I implemented a TabLayout and I want to display my Recyclerview in one of the tabs so I created an adapter:
public class AdapterFrag extends RecyclerView.ViewHolder {
public TextView Longitude;
public TextView Latitude;
public TextView mName;
public RatingBar mRatingbar;
public ProperRatingBar mPriceBar;
public TextView mOperationHours;
public TextView nOperationHours;
public TextView mDescription;
public AdapterFrag(View itemView){
super(itemView);
mName = (TextView) itemView.findViewById(R.id.name_view);
mRatingbar = (RatingBar)
itemView.findViewById(R.id.mstarRatingBar);
mPriceBar = (ProperRatingBar)
itemView.findViewById(R.id.dollarsignratingbar);
mOperationHours = (TextView)
itemView.findViewById(R.id.hoursOfOperation_weekdays_firebase);
nOperationHours = (TextView)
itemView.findViewById(R.id.hoursOfOperation_weekends_firebase);
mDescription = (TextView)
itemView.findViewById(R.id.description_firebase);
}
}
And a model class with getters and setters and a constructor, and I made sure that the names in my database are the same with no funny business like uppercase difference.
public class RestaurantModel {
private static final String TAG ="KARAM" ;
private String name;
private String Description;
private String image;
private String RestaurantId;
private String rating;
private String Price;
private String mOperationHours;
private String Longitude;
private String Latitude;
private String nOperationHours;
public RestaurantModel() {
}
public RestaurantModel(String name, String description, String image, String
restaurantId, String rating, String price, String mOperationHours, String
longitude, String latitude, String nOperationHours) {
this.name = name;
Description = description;
this.image = image;
RestaurantId = restaurantId;
this.rating = rating;
Price = price;
this.mOperationHours = mOperationHours;
Longitude = longitude;
Latitude = latitude;
this.nOperationHours = nOperationHours;
}
public String getnOperationHours() {
return nOperationHours;
}
public void setnOperationHours(String nOperationHours) {
this.nOperationHours = nOperationHours;
}
public String getmOperationHours() {
return mOperationHours;
}
public void setmOperationHours(String mOperationHours) {
this.mOperationHours = mOperationHours;
}
public String getLongitude() {
return Longitude;
}
public void setLongitude(String longitude) {
Longitude = longitude;
}
public String getLatitude() {
return Latitude;
}
public void setLatitude(String latitude) {
Latitude = latitude;
}
public String getPrice() {
return Price;
}
public void setPrice(String price) {
this.Price = price;
}
public String getName() {
return name;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
this.Description = description;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getRestaurantId() {
return RestaurantId;
}
public void setRestaurantId(String restaurantId) {
RestaurantId = restaurantId;
}
public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating = rating;
}
}
In my Main Activity holder activity, i implemented a Viewpagerclass to set fragment manager and the number of tabs like this
public class main_intermediate extends AppCompatActivity {
String uniqueId;
String Entname;
String mName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_intermediate);
Toolbar toolbar = (Toolbar) findViewById(R.id.htab_toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.htab_tabs);
tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager)
findViewById(R.id.htab_viewpager);
final ViewPagerAdapter adapter = new
ViewPagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new
TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener()
{
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
if (getIntent() != null) {
Intent intentres = getIntent();
if (intentres.hasExtra("uniqueId")) {
uniqueId = intentres.getStringExtra("uniqueId");
} else if (getIntent() != null) {
Intent intentbar = getIntent();
if (intentbar.hasExtra("name")) {
mName = intentbar.getStringExtra("name");
if (!mName.isEmpty() && mName != null) {
loadBarAndClubDetails(mName);
}
} else if (getIntent() != null) {
Intent intentent = getIntent();
if (intentent.hasExtra("Entname")) {
Entname = intentent.getStringExtra("Entname");
if (!Entname.isEmpty() && Entname != null) {
loadEntertainmentdetails(mName);
}
}
}
}
}
}
private void loadBarAndClubDetails(String mName) {
}
private void loadEntertainmentdetails(String mName) {
}
public class ViewPagerAdapter extends FragmentPagerAdapter {
int mNumberOfTabs;
ViewPagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumberOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
TabFragment1 tab1 = new TabFragment1();
Bundle bundle = new Bundle();
bundle.putString("uniqueId", uniqueId);
tab1.setArguments(bundle);
return tab1;
case 1:
TabFragment2 tab2 = new TabFragment2();
bundle = new Bundle();
bundle.putString("uniqueId", uniqueId);
tab2.setArguments(bundle);
return tab2;
default:
return null;
}
}
#Override
public int getCount() {
return mNumberOfTabs;
}
}
}
Finally, in my fragment i inflated the recyclerview in the xml file and i set a recyclerview
and then i set the firebaserecycleradapter like this
public class TabFragment1 extends android.support.v4.app.Fragment implements
OnMapReadyCallback {
public TextView Longitude;
public TextView Latitude;
public TextView mName;
public RatingBar mRatingbar;
public ProperRatingBar mPriceBar;
public TextView mOperationHours;
public TextView nOperationHours;
public TextView mDescription;
RecyclerView mRecyclerView;
String resMid;
View mV;
GoogleMap mMap;
DatabaseReference mRestaurantId;
ProgressDialog progressDialog;
private String TAG = "Karam";
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FirebaseDatabase database = FirebaseDatabase.getInstance();
mRestaurantId = database.getReference("Restaurant");
if (getArguments() != null) {
resMid = getArguments().getString("uniqueId");
Log.d(TAG, "everything is safe till here :)" + resMid);
} else { Log.d(TAG, "getArguments is null");}
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_tab_fragment_1, container, false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.mRecyclerView);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
mRestaurantId = mRestaurantId.child(resMid);
FirebaseRecyclerAdapter<RestaurantModel,AdapterFrag> adapter = new
FirebaseRecyclerAdapter<RestaurantModel, AdapterFrag>(
RestaurantModel.class,
R.layout.tab_fragment_1,
AdapterFrag.class,
mRestaurantId
) {
#Override
protected void populateViewHolder(AdapterFrag viewHolder,
RestaurantModel model, int position) {
mDescription.setText(model.getDescription());
mPriceBar.setRating(Integer.parseInt(model.getPrice()));
mRatingbar.setRating(Integer.parseInt(model.getRating()));
mName.setText(model.getName());
mOperationHours.setText(model.getmOperationHours());
nOperationHours.setText(model.getnOperationHours());
}
};
mRecyclerView.setAdapter(adapter);
return view;
}
}
but it is not populating and it is giving me an error like this:
07-22 18:27:20.451 20797-20797/com.example.karam.nlcg E/AndroidRuntime: FATAL
EXCEPTION: main
Process: com.example.karam.nlcg, PID: 20797
com.google.firebase.database.DatabaseException: Can't convert object of type
java.lang.String to type com.example.karam.nlcg.Restaurant.RestaurantModel
at com.google.android.gms.internal.firebase_
database.zzkt.zzb(Unknown Source:259)
at com.google.android.gms.internal.
firebase_database.zzkt.zza(Unknown Source:0)
at com.google.firebase.database.DataSnapshot.getValue(Unknown Source:10)
at com.firebase.ui.database.FirebaseRecyclerAdapter.
parseSnapshot(FirebaseRecyclerAdapter.java:147)
at com.firebase.ui.database.FirebaseRecyclerAdapter.
getItem(FirebaseRecyclerAdapter.java:136)
at com.firebase.ui.database.FirebaseRecyclerAdapter.
onBindViewHolder(FirebaseRecyclerAdapter.java:176)
at android.support.v7.widget.RecyclerView$Adapter.
onBindViewHolder(RecyclerView.java:6673)
at android.support.v7.widget.RecyclerView$Adapter.
bindViewHolder(RecyclerView.java:6714)
at
android.support.v7.widget.RecyclerView$Recycler.
tryBindViewHolderByDeadline(RecyclerView.java:5647)
I read on github it could be a library problem but i dont think so, i think i am missing something but i really cannot know what it is?
if you can explain why i can fix it i just need to know!
Thanks in advance.
You are getting the following error:
Can't convert object of type java.lang.String to type com.example.karam.nlcg.Restaurant.RestaurantModel
Because your mRestaurantId object points to a reference of type String and not of type RestaurantModel. This is happening because you are first initialize it as:
mRestaurantId = database.getReference("Restaurant");
And later you are changing it to:
mRestaurantId = mRestaurantId.child(resMid);
Which obviously is pointing to the a reference of type String. To solve this, just comment/remove this line of code and use only the first one.
See your firebase structure has an attribute menu but your model (RestaurantModel) does not have that attribute.
RestaurantModel has only attributes of String type.
So answer to your question is modify your RestaurantModel.
UPDATED
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FirebaseDatabase database = FirebaseDatabase.getInstance();
mRestaurantId = database.getReference("Restaurant");
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_tab_fragment_1, container, false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.mRecyclerView);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
FirebaseRecyclerAdapter<RestaurantModel,AdapterFrag> adapter = new
FirebaseRecyclerAdapter<RestaurantModel, AdapterFrag>(
RestaurantModel.class,
R.layout.tab_fragment_1,
AdapterFrag.class,
mRestaurantId
)
}
}

Categories