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.
Related
I'm trying to create a code saying "Where the username that is logged in matches the username of a created recipe, only show these database entries in the recyclerview on my MyRecipes.java activity". I'm having trouble working out where to put this potential statement. Looking at my code, where would you put that statement, if or otherwise?
The userLoggedIn and loggedUser is the variable for the currently logged in user.
The thisUser is what I've set as the users pulled from the database when the recyclerview is populating in the recyclerview.java class.
Any help would be greatly appreciated!
RecyclerView.java class
private static String thisUser;
String userLoggedIn = HomeActivity.getUserLogged();
private Context mContext;
private RecipesAdapter mRecipeAdapter;
public void setConfig (RecyclerView recyclerView, Context context, List<Recipes> recipes, List<String> keys){
mContext = context;
mRecipeAdapter = new RecipesAdapter(recipes, keys);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
recyclerView.setAdapter(mRecipeAdapter);
}
class RecipeItemView extends RecyclerView.ViewHolder{
private TextView mTitle;
private TextView mIngredients;
private TextView mMethod;
private TextView mUser;
private String key;
public RecipeItemView(ViewGroup parent){
super(LayoutInflater.from(mContext).inflate(R.layout.recipe_list_item, parent,false));
mTitle = (TextView) itemView.findViewById(R.id.tvTitle);
mMethod = (TextView) itemView.findViewById(R.id.tvMethod);
mIngredients = (TextView) itemView.findViewById(R.id.tvIngredients);
mUser = (TextView) itemView.findViewById(R.id.tvUser);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, RecipeDetails.class);
intent.putExtra("key", key);
intent.putExtra("title", mTitle.getText().toString());
intent.putExtra("ingredients", mIngredients.getText().toString());
intent.putExtra("method", mMethod.getText().toString());
mContext.startActivity(intent);
}
});
}
public void bind(Recipes recipes, String key) {
mTitle.setText(recipes.getTitle());
mIngredients.setText(recipes.getIngredients());
mMethod.setText(recipes.getMethod());
mUser.setText(recipes.getCreatedUser());
thisUser = mUser.getText().toString().trim();
this.key = key;
}
}
public static String getUserLoggedIn(){
return thisUser;
}
class RecipesAdapter extends RecyclerView.Adapter<RecipeItemView> {
private List<Recipes> mRecipeList;
private List<String> mKeys;
public RecipesAdapter(List<Recipes> mRecipeList, List<String> mKeys) {
this.mRecipeList = mRecipeList;
this.mKeys = mKeys;
}
#NonNull
#Override
public RecipeItemView onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new RecipeItemView(parent);
}
#Override
public void onBindViewHolder(#NonNull RecipeItemView holder, int position) {
holder.bind(mRecipeList.get(position), mKeys.get(position));
}
#Override
public int getItemCount() {
return mRecipeList.size();
}
}
}
MyRecipes.java (Where the recycler view populates and shows all the recipes)
String loggedUser = HomeActivity.getUserLogged();
String thisUser = RecyclerViewConfig.getUserLoggedIn();
Button addRecipes;
private RecyclerView mRecyclerView;
private String passedUsername;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_recipes);
passedUsername = getIntent().getStringExtra("loggedUsername1");
mRecyclerView = (RecyclerView) findViewById(R.id.rvRecipes);
new FirebaseDatabaseHelper().readRecipes(new FirebaseDatabaseHelper.DataStatus() {
#Override
public void DataIsLoaded(List<Recipes> recipes, List<String> keys) {
new RecyclerViewConfig().setConfig(mRecyclerView, MyRecipesActivity.this, recipes, keys);
}
#Override
public void DataIsInserted() {
}
#Override
public void DataIsUpdated() {
}
#Override
public void DataIsDeleted() {
}
});
addRecipes = findViewById(R.id.btnAddNewRecipe);
addRecipes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent addrecipe = new Intent(MyRecipesActivity.this, AddRecipes.class);
addrecipe.putExtra("loggedUsername2", passedUsername);
startActivity(addrecipe);
}
});
}
}
If i understand correctly, you need to show the recipes to the user only if he/she is the one who created it? Assuming that, below change in the code will do the trick.
Change your bind() method as follows.
public void bind(Recipes recipes, String key) {
thisUser = mUser.getText().toString().trim();
if(thisUser.equals(recipes.getCreatedUser)) {
mTitle.setText(recipes.getTitle());
mIngredients.setText(recipes.getIngredients());
mMethod.setText(recipes.getMethod());
mUser.setText(recipes.getCreatedUser());
this.key = key;
}
}
Though that is a naive approach, a better approach would be to filter the recipes list with created user when you load data from Firebase with readRecipes() method itself. To do that a query can be used as below(the exact query below might not work for you depending on your DB structure. Change it as needed)
Query query = reference.child("Recipes").orderByChild("userCreated").equalTo(thisUser);
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().
I was just playing around with some code, learning new things, when I ran into this problem... I'm trying to pass a variable from my RecylcerViewAdapter to a method in MainActivity, but I just can't seem to accomplish it.
I tried a lot of different thing with interfaces and casting, but nothing did the trick. Since I'm fairly new to all of this, maybe I'm making a trivial mistake somewhere?
My Interface:
public interface AdapterCallback {
void onMethodCallback(int id);
}
This is my adapter class:
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> {
private List<Post> postList;
private Context context;
private AdapterCallback listener;
public PostAdapter() {
}
public PostAdapter(List<Post> postList, Context context) {
this.postList = postList;
this.context = context;
}
public void setListener(AdapterCallback listener) {
this.listener = listener;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recycler_layout, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder viewHolder, final int position) {
viewHolder.tvTitle.setText(postList.get(position).getTitle());
viewHolder.tvBody.setText(new StringBuilder(postList.get(position).getBody().substring(0, 20)).append("..."));
viewHolder.tvId.setText(String.valueOf(postList.get(position).getUserId()));
viewHolder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int id = postList.get(position).getId();
if (listener != null) {
listener.onMethodCallback(id);
}
}
});
}
#Override
public int getItemCount() {
return postList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView tvTitle;
TextView tvBody;
TextView tvId;
LinearLayout parentLayout;
public ViewHolder(View itemView) {
super(itemView);
tvTitle = itemView.findViewById(R.id.tvTitle);
tvBody = itemView.findViewById(R.id.tvBody);
tvId = itemView.findViewById(R.id.tvId);
parentLayout = itemView.findViewById(R.id.parentLayout);
}
}
}
And my MainActivity:
public class MainActivity extends AppCompatActivity {
public static final String TAG = "MainActivityLog";
private CompositeDisposable disposable = new CompositeDisposable();
#BindView(R.id.rvPosts)
RecyclerView rvPosts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
rvPosts.setHasFixedSize(true);
rvPosts.setLayoutManager(new LinearLayoutManager(this));
populateList();
logItems();
}
private void populateList() {
MainViewModel viewModel = ViewModelProviders.of(MainActivity.this).get(MainViewModel.class);
viewModel.makeQuery().observe(MainActivity.this, new Observer<List<Post>>() {
#Override
public void onChanged(#Nullable List<Post> posts) {
PostAdapter adapter = new PostAdapter(posts, getApplicationContext());
rvPosts.setAdapter(adapter);
}
});
}
public void logItems() {
PostAdapter adapter = new PostAdapter();
adapter.setListener(new AdapterCallback() {
#Override
public void onMethodCallback(int id) {
MainViewModel viewModel = ViewModelProviders.of(MainActivity.this).get(MainViewModel.class);
viewModel.makeSingleQuery(id).observe(MainActivity.this, new Observer<Post>() {
#Override
public void onChanged(#Nullable final Post post) {
Log.d(TAG, "onChanged: data response");
Log.d(TAG, "onChanged: " + post);
}
});
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
disposable.clear();
}
}
The populateList() method works just fine, but the logItems() method is the problem.
So when i click on a view in RecyclerView I expect the log to output the title, description and ID of the post that was clicked. nut nothing happens...
So, any help would be appreciated.
Make adapter global variable i.e. a field. Use the same object to set every properties.
private PostAdapter adapter;
Replace your logItems method with this:
public void logItems() {
adapter.setListener(new AdapterCallback() {
#Override
public void onMethodCallback(int id) {
MainViewModel viewModel = ViewModelProviders.of(MainActivity.this).get(MainViewModel.class);
viewModel.makeSingleQuery(id).observe(MainActivity.this, new Observer<Post>() {
#Override
public void onChanged(#Nullable final Post post) {
Log.d(TAG, "onChanged: data response");
Log.d(TAG, "onChanged: " + post);
}
});
}
});
}
And populateList with this:
private void populateList() {
MainViewModel viewModel = ViewModelProviders.of(MainActivity.this).get(MainViewModel.class);
viewModel.makeQuery().observe(MainActivity.this, new Observer<List<Post>>() {
#Override
public void onChanged(#Nullable List<Post> posts) {
adapter = new PostAdapter(posts, getApplicationContext());
rvPosts.setAdapter(adapter);
logItems();
}
});
}
And don't call logItems() from onCreate
This is how I implement with my ListAdapters:
public class FeedbackListAdapter extends RecyclerView.Adapter<FeedbackListAdapter.ViewHolder> {
private final ArrayList<Feedback> feedbacks;
private View.OnClickListener onItemClickListener;
private View.OnLongClickListener onItemLongClickListener;
private final Context context;
public FeedbackListAdapter(ArrayList<Feedback> feedbacks, Context context) {
this.feedbacks = feedbacks;
this.context = context;
}
public void setItemClickListener(View.OnClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
public void setOnItemLongClickListener(View.OnLongClickListener onItemLongClickListener){
this.onItemLongClickListener = onItemLongClickListener;
}
public class ViewHolder extends RecyclerView.ViewHolder{
final TextView feedback, created, updated;
final LinearLayout mainLayout;
ViewHolder(View iv) {
super(iv);
/*
* Associate layout elements to Java declarations
* */
mainLayout = iv.findViewById(R.id.main_layout);
feedback = iv.findViewById(R.id.feedback);
created = iv.findViewById(R.id.created_string);
updated = iv.findViewById(R.id.updated_string);
}
}
#Override
public int getItemCount() {
return feedbacks.size();
}
#Override
#NonNull
public FeedbackListAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_feedback_table_row, parent, false);
return new FeedbackListAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(final #NonNull FeedbackListAdapter.ViewHolder holder, final int position) {
/*
* Bind data to layout
* */
try{
Feedback feedback = feedbacks.get(position);
holder.feedback.setText(feedback.getContent());
holder.created.setText(feedback.getCreated());
holder.updated.setText(feedback.getUpdated());
holder.mainLayout.setOnClickListener(this.onItemClickListener);
holder.mainLayout.setOnLongClickListener(this.onItemLongClickListener);
holder.mainLayout.setTag(feedback.getDbID());
TypedValue outValue = new TypedValue();
context.getTheme().resolveAttribute(android.R.attr.selectableItemBackground, outValue, true);
holder.mainLayout.setBackgroundResource(outValue.resourceId);
}catch(IndexOutOfBoundsException e){
e.printStackTrace();
}
}
}
In onPopulateList you create an adaptor:
PostAdapter adapter = new PostAdapter(posts, getApplicationContext());
rvPosts.setAdapter(adapter);
However in public void logItems() { you used a different adapter
PostAdapter adapter = new PostAdapter();
adapter.setListener(new AdapterCallback() {
#Override
public void onMethodCallback(int id) {
...
}
});
Therefore the list is being populated with 1 adapter, but you are setting the listener on an unused second adapter.
The fix is to use the same adapter for both. If you make the adapater a field, and don't create a new one inside of logItems, but just set your listener it should work.
i.e.
// as a field in your class
private PostAdapter adapter;
then
// in `populateList()`
adapter = new PostAdapter(posts, getApplicationContext());
rvPosts.setAdapter(adapter);
and
// in `logItems()`
adapter.setListener(new AdapterCallback() {
#Override
public void onMethodCallback(int id) {
...
}
});
In Adapter
public class CustomerListAdapter extends RecyclerView.Adapter<CustomerListAdapter.OrderItemViewHolder> {
private Context mCtx;
ProgressDialog progressDialog;
//we are storing all the products in a list
private List<CustomerModel> customeritemList;
public CustomerListAdapter(Context mCtx, List<CustomerModel> orderitemList) {
this.mCtx = mCtx;
this.customeritemList = orderitemList;
progressDialog = new ProgressDialog(mCtx);
}
#NonNull
#Override
public OrderItemViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.activity_customer_list, null);
return new OrderItemViewHolder(view, mCtx, customeritemList);
}
#Override
public void onBindViewHolder(#NonNull OrderItemViewHolder holder, int position) {
CustomerModel customer = customeritemList.get(position);
try {
//holder.textViewPINo.setText("PINo \n"+Integer.toString( order.getPINo()));
holder.c_name.setText(customer.getCustomerName());
holder.c_address.setText(customer.getAddress());
holder.c_contact.setText(customer.getMobile());
holder.i_name.setText(customer.getInteriorName());
holder.i_contact.setText(customer.getInteriorMobile());
holder.i_address.setText(customer.getAddress());
} catch (Exception E) {
E.printStackTrace();
}
}
#Override
public int getItemCount() {
return customeritemList.size();
}
class OrderItemViewHolder extends RecyclerView.ViewHolder implements View.OnLongClickListener, View.OnClickListener {
AlertDialog.Builder alert;
private Context mCtx;
TextView c_name, c_contact, c_address, i_name, i_contact, i_address;
TextView OrderItemID, MaterialType, Price2, Qty, AQty;
//we are storing all the products in a list
private List<CustomerModel> orderitemList;
public OrderItemViewHolder(View itemView, Context mCtx, List<CustomerModel> orderitemList) {
super(itemView);
this.mCtx = mCtx;
this.orderitemList = orderitemList;
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
// CatelogOrderDetailModel catelogOrderDetailModel = new CatelogOrderDetailModel();
c_name = itemView.findViewById(R.id.customerName);
c_contact = itemView.findViewById(R.id.contact);
c_address = itemView.findViewById(R.id.address);
i_name = itemView.findViewById(R.id.interiorName);
i_address = itemView.findViewById(R.id.interiorAddress);
i_contact = itemView.findViewById(R.id.interiorContact);
}
#Override
public void onClick(View v) {
int position = getAdapterPosition();
CustomerModel orderitem = this.orderitemList.get(position);
}
#Override
public boolean onLongClick(View v) {
int position = getAdapterPosition();
CustomerModel orderitem = this.orderitemList.get(position);
if (v.getId() == itemView.getId()) {
// showUpdateDeleteDialog(order);
try {
} catch (Exception E) {
E.printStackTrace();
}
Toast.makeText(mCtx, "lc: ", Toast.LENGTH_SHORT).show();
}
return true;
}
}
}
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
I have an application project for news media using java programming, I
want to display images for categories from drawable into recylerview
that are based on json-api, is there any one who can help me?
How I do for load image from drawable and combine it with data from json-api into RecylerView can anyone provide specific code here
this is my AdapterCategory.java
public class AdapterCategory extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<Category> items = new ArrayList<>();
private Context ctx;
private OnItemClickListener mOnItemClickListener;
private int c;
public interface OnItemClickListener {
void onItemClick(View view, Category obj, int position);
}
public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mOnItemClickListener = mItemClickListener;
}
// Provide a suitable constructor (depends on the kind of dataset)
public AdapterCategory(Context context, List<Category> items) {
this.items = items;
ctx = context;
}
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView name;
public TextView post_count;
public LinearLayout lyt_parent;
public ImageView imageView;
public ViewHolder(View v) {
super(v);
name = (TextView) v.findViewById(R.id.name);
post_count = (TextView) v.findViewById(R.id.post_count);
imageView = (ImageView)v.findViewById(R.id.image_category);
lyt_parent = (LinearLayout) v.findViewById(R.id.lyt_parent);
//imageView.setImageResource(image_array.length);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_category, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if(holder instanceof ViewHolder) {
final Category c = items.get(position);
ViewHolder vItem = (ViewHolder) holder;
vItem.name.setText(Html.fromHtml(c.title));
vItem.post_count.setText(c.post_count + "");
Picasso.with(ctx).load(imageUri).into(vItem.imageView);
vItem.lyt_parent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(view, c, position);
}
}
});
}
}
public void setListData(List<Category> items){
this.items = items;
notifyDataSetChanged();
}
public void resetListData() {
this.items = new ArrayList<>();
notifyDataSetChanged();
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return items.size();
}
}
This is my FragmentCategory.java for display data
public class FragmentCategory extends Fragment {
private View root_view, parent_view;
private RecyclerView recyclerView;
private SwipeRefreshLayout swipe_refresh;
private AdapterCategory mAdapter;
private Call<CallbackCategories> callbackCall = null;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
root_view = inflater.inflate(R.layout.fragment_category, null);
parent_view = getActivity().findViewById(R.id.main_content);
swipe_refresh = (SwipeRefreshLayout) root_view.findViewById(R.id.swipe_refresh_layout_category);
recyclerView = (RecyclerView) root_view.findViewById(R.id.recyclerViewCategory);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),3));
recyclerView.setHasFixedSize(true);
//set data and list adapter
mAdapter = new AdapterCategory(getActivity(), new ArrayList<Category>());
recyclerView.setAdapter(mAdapter);
// on item list clicked
mAdapter.setOnItemClickListener(new AdapterCategory.OnItemClickListener() {
#Override
public void onItemClick(View v, Category obj, int position) {
ActivityCategoryDetails.navigate((ActivityMain) getActivity(), v.findViewById(R.id.lyt_parent), obj);
}
});
// on swipe list
swipe_refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mAdapter.resetListData();
requestAction();
}
});
requestAction();
return root_view;
}
private void displayApiResult(final List<Category> categories) {
mAdapter.setListData(categories);
swipeProgress(false);
if (categories.size() == 0) {
showNoItemView(true);
}
}
private void requestCategoriesApi() {
API api = RestAdapter.createAPI();
callbackCall = api.getAllCategories();
callbackCall.enqueue(new Callback<CallbackCategories>() {
#Override
public void onResponse(Call<CallbackCategories> call, Response<CallbackCategories> response) {
CallbackCategories resp = response.body();
if (resp != null && resp.status.equals("ok")) {
displayApiResult(resp.categories);
} else {
onFailRequest();
}
}
#Override
public void onFailure(Call<CallbackCategories> call, Throwable t) {
if (!call.isCanceled()) onFailRequest();
}
});
}
private void onFailRequest() {
swipeProgress(false);
if (NetworkCheck.isConnect(getActivity())) {
showFailedView(true, getString(R.string.failed_text));
} else {
showFailedView(true, getString(R.string.no_internet_text));
}
}
private void requestAction() {
showFailedView(false, "");
swipeProgress(true);
showNoItemView(false);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
requestCategoriesApi();
}
}, Constant.DELAY_TIME);
}
#Override
public void onDestroy() {
super.onDestroy();
swipeProgress(false);
if(callbackCall != null && callbackCall.isExecuted()){
callbackCall.cancel();
}
}
private void showFailedView(boolean flag, String message) {
View lyt_failed = (View) root_view.findViewById(R.id.lyt_failed_category);
((TextView) root_view.findViewById(R.id.failed_message)).setText(message);
if (flag) {
recyclerView.setVisibility(View.GONE);
lyt_failed.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_failed.setVisibility(View.GONE);
}
((Button) root_view.findViewById(R.id.failed_retry)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
requestAction();
}
});
}
private void showNoItemView(boolean show) {
View lyt_no_item = (View) root_view.findViewById(R.id.lyt_no_item_category);
((TextView) root_view.findViewById(R.id.no_item_message)).setText(R.string.no_category);
if (show) {
recyclerView.setVisibility(View.GONE);
lyt_no_item.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_no_item.setVisibility(View.GONE);
}
}
private void swipeProgress(final boolean show) {
if (!show) {
swipe_refresh.setRefreshing(show);
return;
}
swipe_refresh.post(new Runnable() {
#Override
public void run() {
swipe_refresh.setRefreshing(show);
}
});
}
And this is my ModeCategory.java
public class Category implements Serializable {
public int id = -1;
public String slug = "";
public String type = "";
public String url = "";
public String title = "";
public String title_plain = "";
public String content = "";
public String excerpt = "";
public String date = "";
public String modified = "";
public String description = "";
public int parent = -1;
public int post_count = -1;
public Author author;
public List<Category> categories = new ArrayList<>();
public List<Comment> comments = new ArrayList<>();
public List<Attachment> attachments = new ArrayList<>();
public CategoryRealm getObjectRealm(){
CategoryRealm c = new CategoryRealm();
c.id = id;
c.url = url;
c.slug = slug;
c.title = title;
c.description = description;
c.parent = parent;
c.post_count = post_count;
return c;
}
}