Hello I implemented search via query using firebaserealtime but now it is not displaying name, photo, or status, the standard thumbnail / profile is displayed when doing the search and clicking the searched item is really the source item. I'm just having trouble displaying the name, photo, status data. could someone help me already tried to put inside onstart but it doesn't work. Thank you very much in advance. any help is welcome. before implementation, a photo, name, status was displayed. What am I doing wrong?
In debug
getName or getStatus no return data :(
But if I do a search by the name of the user and when I click the search the search result in the click event is corresponding to the search name yes it works. problem -> but it's just not displaying photo, name, status.
DB STRUCTURE
MyActivity Code:
public class FindFriendsActivity extends AppCompatActivity
{
FirebaseRecyclerAdapter<Contacts, FindFriendViewHolder> adapter;
private Toolbar mToolbar;
private RecyclerView FindFriendsRecyclerList;
private DatabaseReference UsersRef;
private SearchView searchView;
private Query query;
private FirebaseRecyclerOptions<Contacts> options;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_friends);
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
FindFriendsRecyclerList = (RecyclerView) findViewById(R.id.find_friends_recycler_list);
FindFriendsRecyclerList.setLayoutManager(new LinearLayoutManager(this));
mToolbar = (Toolbar) findViewById(R.id.find_friends_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("Find Friends");
searchView = findViewById(R.id.materialSearchPrincipal);
}
private void fetch(Query query) {
FirebaseRecyclerOptions<Contacts > options =
new FirebaseRecyclerOptions.Builder<Contacts>()
.setQuery(query, new SnapshotParser<Contacts>() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#NonNull
#Override
public Contacts parseSnapshot(#NonNull DataSnapshot snapshot) {
return new Contacts(Objects.requireNonNull(snapshot.child("name").getValue()).toString(),
Objects.requireNonNull(snapshot.child("status").getValue()).toString());
}
})
.build();
adapter = new FirebaseRecyclerAdapter<Contacts, FindFriendViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull FindFriendViewHolder holder, final int position, #NonNull Contacts model)
{
holder.userName.setText(model.getName());
holder.userStatus.setText(model.getStatus());
Picasso.get().load(model.getImage()).placeholder(R.drawable.profile_image).into(holder.profileImage);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
String visit_user_id = getRef(position).getKey();
Intent profileIntent = new Intent(FindFriendsActivity.this, ProfileActivity.class);
profileIntent.putExtra("visit_user_id", visit_user_id);
startActivity(profileIntent);
}
});
}
#NonNull
#Override
public FindFriendViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i)
{
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.users_display_layout, viewGroup, false);
FindFriendViewHolder viewHolder = new FindFriendViewHolder(view);
return viewHolder;
}
};
adapter.startListening();
FindFriendsRecyclerList.setAdapter(adapter);
}
#Override
protected void onStart()
{
super.onStart();
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
Query query = FirebaseDatabase.getInstance().getReference().child("Users");
fetch(query);
adapter.startListening();
}
public static class FindFriendViewHolder extends RecyclerView.ViewHolder
{
TextView userName, userStatus;
CircleImageView profileImage;
FindFriendViewHolder(#NonNull View itemView)
{
super(itemView);
userName = itemView.findViewById(R.id.user_profile_name);
userStatus = itemView.findViewById(R.id.user_status);
profileImage = itemView.findViewById(R.id.users_profile_image);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
searchView.setOnQueryTextListener(new androidx.appcompat.widget.SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
Query query = FirebaseDatabase.getInstance()
.getReference()
.child("Users").orderByChild("name").equalTo(s);
if(s.equals("")){
query = FirebaseDatabase.getInstance()
.getReference()
.child("Users");
}
fetch(query);
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
}
Contacts - Model
public class Contacts {
public String name, status, image;
public Contacts(String name, String status)
{
}
public Contacts(String name, String status, String image) {
this.name = name;
this.status = status;
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
Related
I'm referring this tutorial ==> https://uniqueandrocode.com/add-to-favourites-and-display-favourites-in-recyclerview/ in my project I have bottom navigation...I am trying to add favourites in the first tab and displaying favourites in the second tab in the bottom navigation bar. I'm using Room library.
When activity loads favourites are all blank at first, but when I first row as favourite and go-to favourite tab it displays properly but when I came back to the first tab it fills all the favourites icon automatically (which I have not done I had only done the first row)
Really need help. Thanks in advance.
Dao:
#Dao
public interface FavoriteDao {
#Insert
public void addData(FavoriteList favoriteList);
#Query("select * from favoritelist")
public List<FavoriteList> getFavoriteData();
#Query("SELECT EXISTS (SELECT 1 FROM favoritelist WHERE id=:id)")
public int isFavorite(int id);
#Delete
public void delete(FavoriteList favoriteList);
}
Database:
#Database(entities={FavoriteList.class},version = 1)
public abstract class FavoriteDatabase extends RoomDatabase {
public abstract FavoriteDao favoriteDao();
}
FavoriteList:
#Entity(tableName="favoritelist")
public class FavoriteList {
#PrimaryKey
private int id;
#ColumnInfo(name = "source")
private String source;
#ColumnInfo(name = "author")
private String author;
#ColumnInfo(name = "title")
private String title;
#ColumnInfo(name = "description")
private String description;
#ColumnInfo(name = "url")
private String url;
#ColumnInfo(name = "urlToImage")
private String urlToImage;
#ColumnInfo(name = "publishedAt")
private String publishedAt;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUrlToImage() {
return urlToImage;
}
public void setUrlToImage(String urlToImage) {
this.urlToImage = urlToImage;
}
public String getPublishedAt() {
return publishedAt;
}
public void setPublishedAt(String publishedAt) {
this.publishedAt = publishedAt;
}
}
News fragment:
public class news extends Fragment {
ImageView favbtn;
RecyclerView recyclerView;
SwipeRefreshLayout swipeRefreshLayout;
EditText etQuery;
Button btnSearch;
Adapter adapter;
List<Articles> articles = new ArrayList<>();
public static FavoriteDatabase favoriteDatabase;
public news() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_news, container, false);
swipeRefreshLayout = view.findViewById(R.id.swiprefresh);
etQuery = view.findViewById(R.id.etQuery);
btnSearch = view.findViewById(R.id.btnSearch);
favoriteDatabase= Room.databaseBuilder(getActivity(),FavoriteDatabase.class,"myfavdb").
allowMainThreadQueries().build();
recyclerView = view.findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
final String country = getCountry();
retrieveJson("", country, API_Key);
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!etQuery.getText().toString().equals("")) {
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
retrieveJson(etQuery.getText().toString(), country, API_Key);
}
});
retrieveJson(etQuery.getText().toString(), country, API_Key);
} else {
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
retrieveJson("", country, API_Key);
}
});
retrieveJson("", country, API_Key);
}
}
});
return view;
}
private void showChangeLanguageDialog() {
}
public void retrieveJson(String query, String country, String apiKey) {
swipeRefreshLayout.setRefreshing(true);
Call<Headlines> call;
if (!etQuery.getText().toString().equals("")) {
call = ApiClient.getInstance().getApi().getSpecifiedData(query, apiKey);
} else {
call = ApiClient.getInstance().getApi().getHeadLines(country, apiKey);
}
call.enqueue(new Callback<Headlines>() {
#Override
public void onResponse(Call<Headlines> call, Response<Headlines> response) {
if (response.isSuccessful() && response.body().getArticles() != null) {
swipeRefreshLayout.setRefreshing(false);
// articles.clear();
articles = response.body().getArticles();
adapter = new Adapter(getContext(), articles);
recyclerView.setAdapter(adapter);
}
}
#Override
public void onFailure(Call<Headlines> call, Throwable t) {
swipeRefreshLayout.setRefreshing(false);
Toast.makeText(getContext(), t.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
});
}
public String getCountry() {
Locale locale = Locale.getDefault();
String country = locale.getCountry();
return country.toLowerCase();
}
}
Adapter:
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
Context context;
List<Articles> articles;
public Adapter(Context context, List<Articles> articles) {
this.context = context;
this.articles = articles;
}
#NonNull
#Override
public Adapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final Adapter.ViewHolder holder, final int position) {
final Articles a = articles.get(position);
String imageUrl = a.getUrlToImage();
String url = a.getUrl();
holder.tvTitle.setText(a.getTitle());
Picasso.get().load(imageUrl).into(holder.imageView);
holder.tvSource.setText(a.getSource().getName());
holder.tvDate.setText(dateTime(a.getPublishedAt()));
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context,DetailedActivity.class);
intent.putExtra("title",a.getTitle());
intent.putExtra("source",a.getSource().getName());
intent.putExtra("time",dateTime(a.getPublishedAt()));
intent.putExtra("desc",a.getDescription());
intent.putExtra("imageUrl",a.getUrlToImage());
intent.putExtra("url",a.getUrl());
context.startActivity(intent);
}
});
if (news.favoriteDatabase.favoriteDao().isFavorite(articles.get(position).getId())==1)
holder.bookmark.setImageResource(R.drawable.ic_bookmark);
else
holder.bookmark.setImageResource(R.drawable.ic_baseline_bookmark_border_24);
holder.bookmark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FavoriteList favoriteList = new FavoriteList();
int id = articles.get(position).getId();
String source = articles.get(position).getSource().getName();
String author = articles.get(position).getAuthor();
String publishedAt = articles.get(position).getPublishedAt();
String description = articles.get(position).getDescription();
String title = articles.get(position).getTitle();
String url = articles.get(position).getUrl();
String urlToImage = articles.get(position).getUrlToImage();
favoriteList.setId(id);
favoriteList.setAuthor(author);
favoriteList.setDescription(description);
favoriteList.setSource(source);
favoriteList.setPublishedAt(publishedAt);
favoriteList.setTitle(title);
favoriteList.setUrl(url);
favoriteList.setUrlToImage(urlToImage);
favoriteList.setPublishedAt(dateTime(articles.get(position).getPublishedAt()));
if (news.favoriteDatabase.favoriteDao().isFavorite(id)!=1){
holder.bookmark.setImageResource(R.drawable.ic_bookmark);
news.favoriteDatabase.favoriteDao().addData(favoriteList);
}else {
holder.bookmark.setImageResource(R.drawable.ic_baseline_bookmark_border_24);
news.favoriteDatabase.favoriteDao().delete(favoriteList);
}
}
});
}
#Override
public int getItemCount() {
return articles.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView tvTitle, tvSource, tvDate;
ImageView imageView;
ImageButton bookmark;
CardView cardView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
tvTitle = itemView.findViewById(R.id.tvId);
tvSource = itemView.findViewById(R.id.tvSource);
tvDate = itemView.findViewById(R.id.tvDate);
imageView = itemView.findViewById(R.id.image);
cardView = itemView.findViewById(R.id.cardView);
bookmark = itemView.findViewById(R.id.favrr);
}
}
Steps to debug:
Add 2-3 items as Favs.
Restart the Application.
Check if it shows those items as fav after restarting application .
also add logs to those if conditions where you are changing the drawables.
After looking at your JSON it looks like id is what creating problems. Id is null for all your json items so when fav. one it shows fav. to all.
Solution : Use another field to check if the data is added to fav.list
Delete will not work either
Try
#Query("DELETE FROM favoritelist WHERE title = :title")
void deleteByUserId(String title);
To delete item
Also https://github.com/amitshekhariitbhu/Android-Debug-Database
check this library to debug your database
i have a recycler view that has many shops in my app. each app when clicked opens a new activity that should display all the details of that specific shop.
now i created the onclick listener and everything is working fine and i am even going to the next activity which is detailsActivity.
My problem is that how can i pass the information of each individual shop into the detailsActivity after it has been clicked in the HomeActivity.
here is my Shop Class:
private String name;
private String country;
private String address;
private String location;
private String ShopHeaderImg;
private String ShopProfileImg;
private String shopPID;
//constructor
public Shop(){
}
//constructor with parameters
public Shop(String name, String country, String address, String location, String shopHeaderImg, String shopProfileImg, String shopPID) {
this.name = name;
this.country = country;
this.address = address;
this.location = location;
this.ShopHeaderImg = shopHeaderImg;
ShopProfileImg = shopProfileImg;
this.shopPID = shopPID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
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;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getShopHeaderImg() {
return ShopHeaderImg;
}
public void setShopHeaderImg(String shopHeaderImg) {
ShopHeaderImg = shopHeaderImg;
}
public String getShopProfileImg() {
return ShopProfileImg;
}
public void setShopProfileImg(String shopProfileImg) {
ShopProfileImg = shopProfileImg;
}
public String getShopPID() {
return shopPID;
}
public void setShopPID(String shopPID) {
this.shopPID = shopPID;
}
}
and here is my HomeActivity:
private FirebaseFirestore firebaseFirestore;
private RecyclerView FirestoreList;
private FirestoreRecyclerAdapter adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
FirestoreList = findViewById(R.id.recycler_view);
firebaseFirestore = FirebaseFirestore.getInstance();
Query q = firebaseFirestore.collection("Shops");
//recycle options
FirestoreRecyclerOptions<Shop> options = new FirestoreRecyclerOptions.Builder<Shop>()
.setQuery(q, Shop.class)
.build();
adapter = new FirestoreRecyclerAdapter<Shop, ShopViewHolder>(options) {
#NonNull
#Override
public ShopViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.shop_item,parent,false);
//onclick of cardview
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context, DetailsActivity.class);
context.startActivity(intent);
}
});
return new ShopViewHolder(view);
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onBindViewHolder(#NonNull ShopViewHolder holder, int position, #NonNull Shop model) {
holder.list_name.setText(model.getName());
holder.list_location.setText(model.getLocation());
holder.list_uid.setText(model.getShopPID());
holder.setHeaderImage(getApplicationContext(),model.getShopHeaderImg());
holder.list_profileImage(getApplicationContext(),model.getShopProfileImg());
}
};
FirestoreList.setHasFixedSize(true);
FirestoreList.setLayoutManager(new LinearLayoutManager(this));
FirestoreList.setAdapter(adapter);
}
private class ShopViewHolder extends RecyclerView.ViewHolder {
private TextView list_name;
private TextView list_location;
private TextView list_uid;
private ImageView header_img;
private ImageView list_profileImage;
public ShopViewHolder(#NonNull View itemView) {
super(itemView);
list_name = itemView.findViewById(R.id.list_name);
list_location = itemView.findViewById(R.id.list_location);
list_uid = itemView.findViewById(R.id.list_uid);
header_img = itemView.findViewById(R.id.header_img);
list_profileImage = itemView.findViewById(R.id.list_profileImage);
}
public void setHeaderImage(final Context c , final String Image) {
final ImageView headerImg = (ImageView)itemView.findViewById(R.id.header_img);
Picasso.get().load(Image).into(headerImg);
}
public void list_profileImage(final Context c , final String image) {
final ImageView profileImg = (ImageView)itemView.findViewById(R.id.list_profileImage);
Picasso.get().load(image).into(profileImg);
}
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
this is my DetailsActivity:
public class DetailsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
}
}
now when i click on any of the shops cards or images it opens up the DetailsActivity. my problem is with how to get that specific shops info into the new detailsActivity from the DB such as name,location,address etc.
Nidhessh is right to ask you to move the onCLickListener to the onBindViewHolder, but I would do it this way:
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onBindViewHolder(#NonNull ShopViewHolder holder, int position, #NonNull Shop model) {
holder.list_name.setText(model.getName());
holder.list_location.setText(model.getLocation());
holder.list_uid.setText(model.getShopPID());
holder.setHeaderImage(getApplicationContext(),model.getShopHeaderImg());
holder.list_profileImage(getApplicationContext(),model.getShopProfileImg());
//add this lines
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, DetailsActivity.class);
intent.putExtra("shopModel", model);
context.startActivity(intent);
}
});
Make your Shop class implement Serializable, like this:
public class Shop implements Serializable {
...
//all remains the same in that class
}
After in your DetailsActivity write this to get the selected shop model:
Shop shopModel = getIntent().getSerializableExtra("shopModel");
first of all, create setOnClickListener in onBindViewHolder
holder.list_name..setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Shop shopmodel= shoparray.get( holder.getAdapterPosition());
Intent intent = new Intent(context, DetailsActivity.class);
intent.putExtra("keyName", shopmodel.getName());
context.startActivity(intent);
}
});
for retrieving values in detail activity
Bundle extras = intent.getExtras();
if(extras != null)
String data = extras.getString("keyName");
My RecyclerView not show any data from Firebase. I don't see any errors at logcat so I don't know why. I followed guide from youtube video. But still nothing. I'm using android 8.0 and API 27. Hope Somebody can help.
My Main Activity Code:
public class ViewProduct extends AppCompatActivity {
DatabaseReference ref;
ArrayList<Model> list;
private RecyclerView recyclerView;
private RecyclerView.Adapter viewHolder;
private RecyclerView.LayoutManager layoutManager;
SearchView searchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_product) ;
ref = FirebaseDatabase.getInstance().getReference().child("buddymealplanneruser").
child("Products");
recyclerView = findViewById(R.id.stallproductRecyclerView);
//recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
//SEARCH VIEW
searchView = findViewById(R.id.searchProductStall);
//ADAPTER
list = new ArrayList<>();
viewHolder = new ViewHolder(list);
recyclerView.setAdapter(viewHolder);
}
#Override
protected void onRestart() {
super.onRestart();
if (ref!=null)
{
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists())
{
//list = new ArrayList<>();
list.clear();
for(DataSnapshot ds : dataSnapshot.getChildren())
{
list.add(ds.getValue(Model.class));
}
//ViewHolder viewHolder = new ViewHolder(list);
//recyclerView.setAdapter(viewHolder);
viewHolder.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(ViewProduct.this, databaseError.getMessage(),
Toast.LENGTH_SHORT).show();
}
});
}
if (searchView !=null)
{
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s)
{
return false;
}
#Override
public boolean onQueryTextChange(String s) {
search(s);
return true;
}
});
}
}
private void search(String str) {
ArrayList<Model> myList = new ArrayList<>();
for(Model object : list)
{
if(object.getProductName().toLowerCase().contains(str.toLowerCase()))
{
myList.add(object);
}
}
ViewHolder viewHolder = new ViewHolder(myList);
recyclerView.setAdapter(viewHolder);
}
}
My Adapter:
public class ViewHolder extends RecyclerView.Adapter<ViewHolder.MyViewHolder> {
ArrayList<Model> list;
public ViewHolder (ArrayList<Model> list)
{
this.list=list;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_product, viewGroup,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, int i) {
myViewHolder.productName.setText(list.get(i).getProductName());
myViewHolder.productCalorie.setText(list.get(i).getProductCalorie());
myViewHolder.StallId.setText(list.get(i).getStallId());
myViewHolder.productType.setText(list.get(i).getProductType());
myViewHolder.productServing.setText(list.get(i).getProductServing());
myViewHolder.statusProduct.setText(list.get(i).getStatusProduct());
}
#Override
public int getItemCount()
{
return list.size();
}
class MyViewHolder extends RecyclerView.ViewHolder
{
TextView productName, productCalorie, StallId;
TextView productType, productServing, statusProduct;
ImageView productImageView;
public MyViewHolder (#NonNull View itemView){
super((itemView));
productName = itemView.findViewById(R.id.productTitle);
productCalorie = itemView.findViewById(R.id.productDescriptionCalorie);
StallId = itemView.findViewById(R.id.productDescriptionStallId);
productType = itemView.findViewById(R.id.productDescriptionType);
productServing=itemView.findViewById(R.id.productDescriptionServing);
statusProduct=itemView.findViewById(R.id.productDescriptionAvailibility);
//productImageView = itemView.findViewById(R.id.productImageView);
}
}
}
My Model :
package com.example.buddymealplannerstall.Child;
import android.view.Display;
public class Model {
//String productName, productImage, productCalorie, StallId, productType, productServing, statusProduct;
private String StallId;
private String productCalorie;
private String productImage;
private String productName;
private String productServing;
private String productType;
private String statusProduct;
public Model (String StallId,
String productCalorie,
String productImage,
String productName,
String productServing,
String productType,
String statusProduct){
this.StallId = StallId;
this.productCalorie = productCalorie;
this.productImage = productImage;
this.productName = productName;
this.productServing = productServing;
this.productType = productType;
this.statusProduct = statusProduct;
}
public Model(){
}
public String getStallId() {
return StallId;
}
public void setStallId(String stallId) {
StallId = stallId;
}
public String getProductCalorie() {
return productCalorie;
}
public void setProductCalorie(String productCalorie) {
this.productCalorie = productCalorie;
}
public String getProductImage() {
return productImage;
}
public void setProductImage(String productImage) {
this.productImage = productImage;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductServing() {
return productServing;
}
public void setProductServing(String productServing) {
this.productServing = productServing;
}
public String getProductType() {
return productType;
}
public void setProductType(String productType) {
this.productType = productType;
}
public String getStatusProduct() {
return statusProduct;
}
public void setStatusProduct(String statusProduct) {
this.statusProduct = statusProduct;
}
}
Screen Shot of my firebase and my apps.
firebase
my app
According to your comment:
yes, buddymealplanner is my project's name
Please note that there is no need to add the name of your project as a child in the reference. So please change the following line of code:
ref = FirebaseDatabase.getInstance().getReference().child("buddymealplanneruser").
child("Products");
Simply to:
ref = FirebaseDatabase.getInstance().getReference().child("Products");
I dont think you are populating your list, you are sending it empty. From what I can see, you only add items to the list when you are restarting the activity. Try either populating it before sendinig the list, or changing the onRestart() for an onStart() or an onResume().
This is my adapter for recycle view
CategoryAdapter Class
public class CategoryRAdapter extends RecyclerView.Adapter<CategoryRAdapter.MyViewHolder> {
private Context mcontext;
private List<Food> mData;
RequestOptions option;
public CategoryRAdapter(Context mcontext, List<Food> mData) {
this.mcontext = mcontext;
this.mData = mData;
option = new RequestOptions().centerCrop().placeholder(R.drawable.loading_shape).error(R.drawable.loading_shape);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.food_row, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Food current = mData.get(position);
holder.tv_Name.setText(current.getName());
holder.tv_Rating.setText(current.getRating());
holder.tv_Descip.setText(current.getDescrip());
holder.tv_Category.setText(current.getCateg());
Glide.with(mcontext).load(mData.get(position).getImages()).apply(option).into(holder.img_Thumbnail);
}
#Override
public int getItemCount() {
return mData.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView tv_Name;
TextView tv_Rating;
TextView tv_Descip;
TextView tv_Category;
ImageView img_Thumbnail;
public MyViewHolder(View itemView) {
super(itemView);
tv_Name = itemView.findViewById(R.id.food_name);
tv_Rating = itemView.findViewById(R.id.rating);
tv_Descip = itemView.findViewById(R.id.desc);
tv_Category = itemView.findViewById(R.id.category);
img_Thumbnail = itemView.findViewById(R.id.thumbnail);
}
}
}
This is my model
Food Class
public class Food {
String Name;
String Images;
String Descrip;
String Rating;
String Categ;
public Food() {
}
public Food(String name, String images, String descrip, String rating, String categ) {
this.Name = name;
this.Images = images;
this.Descrip = descrip;
this.Rating = rating;
this.Categ = categ;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getImages() {
return Images;
}
public void setImages(String images) {
Images = images;
}
public String getDescrip() {
return Descrip;
}
public void setDescrip(String descrip) {
Descrip = descrip;
}
public String getRating() {
return Rating;
}
public void setRating(String rating) {
Rating = rating;
}
public String getCateg() {
return Categ;
}
public void setCateg(String categ) {
Categ = categ;
}
}
My mian activity
CategoryActivity Class
public class CategoriaActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private List<Food> dbObjects;
private RecyclerView.Adapter adapter;
private AlertDialog.Builder dialogBuilder;
private AlertDialog dialog;
TextView l_nombre,l_precio;
Button l_finalizar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_categoria);
recyclerView = findViewById(R.id.recycle_id);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
dbObjects = new ArrayList<>();
ParseQuery<ParseObject> query = ParseQuery.getQuery("Category");
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> objList, ParseException e) {
if (e == null) {
for (ParseObject obj : objList) {
Food food = new Food();
food.setName(obj.getString("Name"));
food.setDescrip(obj.getString("Descrip"));
food.setRating(obj.getString("Rating"));
food.setCateg(obj.getString("Categ"));
food.setImages(obj.getString("Images"));
dbObjects.add(food);
}
} else {
FancyToast.makeText(CategoriaActivity.this, "Error: " + e.getMessage(), FancyToast.LENGTH_SHORT, FancyToast.ERROR, true).show();
}
}
});
adapter = new CategoryRAdapter(this, dbObjects);
recyclerView.setAdapter(adapter);
FloatingActionButton fab = findViewById(R.id.shoppingFlot);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
carritopop();
}
});
}
private void carritopop() {
dialogBuilder = new AlertDialog.Builder(this);
View view = getLayoutInflater().inflate(R.layout.pop_cart,null);
l_finalizar = view.findViewById(R.id.l_finalizar);
l_finalizar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pago();
}
});
dialogBuilder.setView(view);
dialog = dialogBuilder.create();
dialog.show();
}
private void pago() {
Intent intent = new Intent(CategoriaActivity.this, PagoActivity.class);
startActivity(intent);
}
}
I dont know whats wrong with the code, the recycle view aint working, it aint showing any items, i would really appreciate if someone could help me out and notice something wrong in my code
Call adapter.notifyDataSetChanged() in your query done callback, this will notify the adapter that the list has changed. This is happening because when you set the adapter, the list was empty as the query was running in background. Once it completes, you have to tell the adapter that new data has been added to list:
if (e == null) {
for (ParseObject obj : objList) {
...
}
adapter.notifyDataSetChanged();
}
Also, create your adapter before you send the query otherwise it may result in NullPointerException in case data is loaded before the next statement executes (highly unlikely but never hurts to be safe).
dbObjects = new ArrayList<>();
adapter = new CategoryRAdapter(this, dbObjects);
ParseQuery<ParseObject> query = ParseQuery.getQuery("Category");
I recommend you to use RxJava2 to user asynchronous methods, it's awesome... And about the problem, maybe your data is not ready when you're already creating the adapter with the ArrayList.
Try to move the recyclerView.setAdapter() to inside the FindCallback after create the Food Objects.
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