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
Related
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;
}
}
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 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.
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.
This question already has answers here:
Fragment cannot be converted to Context
(4 answers)
Closed 5 years ago.
I want to parse JSON and display with RecyclerView and CardView in Android. I have a tabHost menu and there are three fragments activities of it. I put all my code for the CardView into one of the fragment, but the code has errors when I use "this" to call GridLayoutManager and CustomAdapter.
This is the code in fragment activity, the error is in onViewCreated:
final TextView tv = (TextView) view.findViewById(R.id.tv);
adapter = new CustomAdapter(this,data_list);
The error message is:
Error:(75, 51) error: incompatible types: Tab2Fragment cannot be converted to Context, GridLayoutManager(android.content.Context, int) in GridLayoutManager cannot applied to (com.xxx.xxx.xxx.Tab2Fragment)
public class Tab2Fragment extends Fragment {
private RecyclerView recyclerView;
private GridLayoutManager gridLayoutManager;
private CustomAdapter adapter;
private List<MyData> data_list;
public Tab2Fragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_tab2, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SharedPreferences settings = this.getActivity().getSharedPreferences("user", Context.MODE_PRIVATE);
String username = settings.getString("username","default"); // get back the stored share preferences
final TextView tv = (TextView) view.findViewById(R.id.tv);
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
data_list = new ArrayList<>();
load_data_from_server(username);
gridLayoutManager = new GridLayoutManager(this,2);
recyclerView.setLayoutManager(gridLayoutManager);
adapter = new CustomAdapter(this,data_list);
recyclerView.setAdapter(adapter);
}
private void load_data_from_server(final String username) {
AsyncTask<String,Void,Void> task = new AsyncTask<String, Void, Void>() {
#Override
protected Void doInBackground(String... strings) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://www.tootcards.com/instaidea/cardapi.php?username="+strings[0])
.build();
try {
Response response = client.newCall(request).execute();
JSONArray array = new JSONArray(response.body().string());
for (int i=0; i<array.length(); i++){
JSONObject object = array.getJSONObject(i);
MyData data = new MyData(object.getInt("shop_id"),object.getString("shop_name"),
object.getString("cardimg"));
data_list.add(data);
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
System.out.println("End of content");
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
adapter.notifyDataSetChanged();
}
};
task.execute(username);
}
#Override
public void onDetach() {
super.onDetach();
}
}
The code in CustomAdapter.java:
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
private Context context;
private List<MyData> my_data;
public CustomAdapter(Context context, List<MyData> my_data) {
this.context = context;
this.my_data = my_data;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.card,parent,false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.description.setText(my_data.get(position).getDescription());
Glide.with(context).load(my_data.get(position).getImage_link()).into(holder.imageView);
}
#Override
public int getItemCount() {
return my_data.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView description;
public ImageView imageView;
public ViewHolder(View itemView) {
super(itemView);
description = (TextView) itemView.findViewById(R.id.description);
imageView = (ImageView) itemView.findViewById(R.id.image);
}
}
}
The code in myData.java:
class MyData {
private int id;
private String description, image_link;
public MyData(int id, String description, String image_link) {
this.id = id;
this.description = description;
this.image_link = image_link;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImage_link() {
return image_link;
}
public void setImage_link(String image_link) {
this.image_link = image_link;
}
}
Any help will be appreciated.
Change
this
to
getActivity()
try this
final TextView tv = (TextView) view.findViewById(R.id.tv); adapter = new CustomAdapter(getActivity(), data_list);
or
final TextView tv = (TextView) view.findViewById(R.id.tv); adapter = new CustomAdapter(getContext(), data_list);