This question already has answers here:
recyclerview No adapter attached; skipping layout
(38 answers)
Closed 1 year ago.
Don't know why it says "No adapter attached"
I set the layout manager and the recycler view, in middle of showProducts(); method i also set the adapter to the recycler view and still says: "No adapter attached" Can't find where is the issue, i'll gladly accept some help. Thanks folks!
Nothing shows on screen for the following code:
Main activity:
public class MainActivity extends AppCompatActivity {
private RecyclerView rView;
private RecyclerView.LayoutManager layoutManager;
private List<Product> products;
private ProductAdapter productAdapter;
private DatabaseReference mDataBase;
private CardView cardView;
//Product
private String id;
private String name;
private String author;
private String genre;
private String description;
private double price;
private int stock;
private String image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
products = new ArrayList<Product>();
mDataBase = FirebaseDatabase.getInstance().getReference();
cardView = (CardView) findViewById(R.id.cardView);
layoutManager = new LinearLayoutManager(this);
rView = (RecyclerView) findViewById(R.id.recyclerView);
rView.setHasFixedSize(true);
rView.setLayoutManager(layoutManager);
showProducts();
registerForContextMenu(rView);
}
private void showProducts() {
mDataBase.child("Products").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
products.clear();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
name = ds.child("title").getValue().toString();
author = ds.child("author").getValue().toString();
genre = ds.child("genre").getValue().toString();
description = ds.child("description").getValue().toString();
price = Double.parseDouble(ds.child("price").getValue().toString());
stock = Integer.parseInt(ds.child("stock").getValue().toString());
image = ds.child("image").getValue().toString();
id = ds.getKey();
Product product = new Product(id, name, author, genre, description, price, stock, image);
products.add(product);
}
productAdapter = new ProductAdapter(products, R.layout.recycler_view, new ProductAdapter.OnItemClickListener() {
#Override
public void onItemClick(Product product, int position) {
}
}, new ProductAdapter.OnButtonClickListener() {
#Override
public void onButtonClick(Product product, int position) {
}
});
}
rView.setAdapter(productAdapter);
}
// Observa como pasamos el activity, con this. Podríamos declarar
// Activity o Context en el constructor y funcionaría pasando el mismo valor, this
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
Adapter:
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ViewHolder>{
private Context context;
private List<Product> products;
private int layout;
private OnItemClickListener itemClickListener;
private OnButtonClickListener btnClickListener;
public ProductAdapter(List<Product> products, int layout, OnItemClickListener itemListener, OnButtonClickListener btnListener) {
this.products = products;
this.layout = layout;
this.itemClickListener = itemListener;
this.btnClickListener = btnListener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(layout, parent, false);
context = parent.getContext();
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.bind(products.get(position), itemClickListener, btnClickListener);
}
#Override
public int getItemCount() {
return products.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView name;
public TextView author;
public TextView genre;
public TextView description;
public TextView price;
public TextView stock;
public ImageView image;
public Button btnDelete;
public ViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.textViewProductName);
author = (TextView) itemView.findViewById(R.id.textViewProductAuthor);
genre = (TextView) itemView.findViewById(R.id.textViewProductGenre);
description = (TextView) itemView.findViewById(R.id.textViewProductDescription);
price = (TextView) itemView.findViewById(R.id.textViewProductPrice);
stock = (TextView) itemView.findViewById(R.id.textViewProductStock);
image = (ImageView) itemView.findViewById(R.id.imageViewProduct);
btnDelete = (Button) itemView.findViewById(R.id.buttonDeleteCity);
}
public void bind(final Product product, final OnItemClickListener itemListener, final OnButtonClickListener btnListener) {
name.setText(product.getName());
description.setText(product.getDescription());
price.setText((int) product.getPrice());
Picasso.get().load(product.getImage()).fit().into(image);
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btnListener.onButtonClick(product, getAdapterPosition());
}
});
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemListener.onItemClick(product, getAdapterPosition());
}
});
}
}
public interface OnItemClickListener {
void onItemClick(Product product, int position);
}
public interface OnButtonClickListener {
void onButtonClick(Product product, int position);
}
}
Bind Adapter in onCreate
Use it like this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
products = new ArrayList<Product>();
mDataBase = FirebaseDatabase.getInstance().getReference();
cardView = (CardView) findViewById(R.id.cardView);
layoutManager = new LinearLayoutManager(this);
rView = (RecyclerView) findViewById(R.id.recyclerView);
rView.setHasFixedSize(true);
rView.setLayoutManager(layoutManager);
rView.setAdapter(productAdapter);
showProducts();
registerForContextMenu(rView);
}
private void showProducts() {
mDataBase.child("Products").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
products.clear();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
name = ds.child("title").getValue().toString();
author = ds.child("author").getValue().toString();
genre = ds.child("genre").getValue().toString();
description = ds.child("description").getValue().toString();
price = Double.parseDouble(ds.child("price").getValue().toString());
stock = Integer.parseInt(ds.child("stock").getValue().toString());
image = ds.child("image").getValue().toString();
id = ds.getKey();
Product product = new Product(id, name, author, genre, description, price, stock, image);
products.add(product);
}
productAdapter = new ProductAdapter(products, R.layout.recycler_view, new ProductAdapter.OnItemClickListener() {
#Override
public void onItemClick(Product product, int position) {
}
}, new ProductAdapter.OnButtonClickListener() {
#Override
public void onButtonClick(Product product, int position) {
}
});
}
productAdapter.notifyDataStateChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
Related
I had ask same question 1 day ago and my question got closed so i ask it again.
Don't know why it says "No adapter attached"
I set the layout manager and the recycler view, in middle of showProducts(); method i also set the adapter to the recycler view and still says: "No adapter attached" Can't find where is the issue, i'll gladly accept some help. Thanks folks!
Nothing shows on screen for the following code:
Main activity:
public class MainActivity extends AppCompatActivity {
private RecyclerView rView;
private RecyclerView.LayoutManager layoutManager;
private List<Product> products;
private ProductAdapter productAdapter;
private DatabaseReference mDataBase;
private CardView cardView;
//Product
private String id;
private String name;
private String author;
private String genre;
private String description;
private double price;
private int stock;
private String image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
products = new ArrayList<Product>();
mDataBase = FirebaseDatabase.getInstance().getReference();
cardView = (CardView) findViewById(R.id.cardView);
layoutManager = new LinearLayoutManager(this);
rView = (RecyclerView) findViewById(R.id.recyclerView);
rView.setHasFixedSize(true);
rView.setLayoutManager(layoutManager);
showProducts();
registerForContextMenu(rView);
}
private void showProducts() {
mDataBase.child("Products").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
products.clear();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
name = ds.child("title").getValue().toString();
author = ds.child("author").getValue().toString();
genre = ds.child("genre").getValue().toString();
description = ds.child("description").getValue().toString();
price = Double.parseDouble(ds.child("price").getValue().toString());
stock = Integer.parseInt(ds.child("stock").getValue().toString());
image = ds.child("image").getValue().toString();
id = ds.getKey();
Product product = new Product(id, name, author, genre, description, price, stock, image);
products.add(product);
}
productAdapter = new ProductAdapter(products, R.layout.recycler_view, new ProductAdapter.OnItemClickListener() {
#Override
public void onItemClick(Product product, int position) {
}
}, new ProductAdapter.OnButtonClickListener() {
#Override
public void onButtonClick(Product product, int position) {
}
});
}
rView.setAdapter(productAdapter);
}
// Observa como pasamos el activity, con this. Podríamos declarar
// Activity o Context en el constructor y funcionaría pasando el mismo valor, this
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
Adapter:
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ViewHolder>{
private Context context;
private List<Product> products;
private int layout;
private OnItemClickListener itemClickListener;
private OnButtonClickListener btnClickListener;
public ProductAdapter(List<Product> products, int layout, OnItemClickListener itemListener, OnButtonClickListener btnListener) {
this.products = products;
this.layout = layout;
this.itemClickListener = itemListener;
this.btnClickListener = btnListener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(layout, parent, false);
context = parent.getContext();
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.bind(products.get(position), itemClickListener, btnClickListener);
}
#Override
public int getItemCount() {
return products.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView name;
public TextView author;
public TextView genre;
public TextView description;
public TextView price;
public TextView stock;
public ImageView image;
public Button btnDelete;
public ViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.textViewProductName);
author = (TextView) itemView.findViewById(R.id.textViewProductAuthor);
genre = (TextView) itemView.findViewById(R.id.textViewProductGenre);
description = (TextView) itemView.findViewById(R.id.textViewProductDescription);
price = (TextView) itemView.findViewById(R.id.textViewProductPrice);
stock = (TextView) itemView.findViewById(R.id.textViewProductStock);
image = (ImageView) itemView.findViewById(R.id.imageViewProduct);
btnDelete = (Button) itemView.findViewById(R.id.buttonDeleteCity);
}
public void bind(final Product product, final OnItemClickListener itemListener, final OnButtonClickListener btnListener) {
name.setText(product.getName());
description.setText(product.getDescription());
price.setText((int) product.getPrice());
Picasso.get().load(product.getImage()).fit().into(image);
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btnListener.onButtonClick(product, getAdapterPosition());
}
});
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemListener.onItemClick(product, getAdapterPosition());
}
});
}
}
public interface OnItemClickListener {
void onItemClick(Product product, int position);
}
public interface OnButtonClickListener {
void onButtonClick(Product product, int position);
}
}
Move this line inside if condition rView.setAdapter(productAdapter); in your showProducts function
like below
private void showProducts() {
mDataBase.child("Products").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
products.clear();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
name = ds.child("title").getValue().toString();
author = ds.child("author").getValue().toString();
genre = ds.child("genre").getValue().toString();
description = ds.child("description").getValue().toString();
price = Double.parseDouble(ds.child("price").getValue().toString());
stock = Integer.parseInt(ds.child("stock").getValue().toString());
image = ds.child("image").getValue().toString();
id = ds.getKey();
Product product = new Product(id, name, author, genre, description, price, stock, image);
products.add(product);
}
productAdapter = new ProductAdapter(products, R.layout.recycler_view, new ProductAdapter.OnItemClickListener() {
#Override
public void onItemClick(Product product, int position) {
}
}, new ProductAdapter.OnButtonClickListener() {
#Override
public void onButtonClick(Product product, int position) {
}
}); rView.setAdapter(productAdapter); }
}
// Observa como pasamos el activity, con this. Podríamos declarar
// Activity o Context en el constructor y funcionaría pasando el mismo valor, this
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
ProductAdapter productAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
products = new ArrayList<Product>();
mDataBase = FirebaseDatabase.getInstance().getReference();
cardView = (CardView) findViewById(R.id.cardView);
productAdapter = new ProductAdapter(products, R.layout.recycler_view, new ProductAdapter.OnItemClickListener() {
#Override
public void onItemClick(Product product, int position) {
}
}, new ProductAdapter.OnButtonClickListener() {
#Override
public void onButtonClick(Product product, int position) {
}
});
layoutManager = new LinearLayoutManager(this);
rView = (RecyclerView) findViewById(R.id.recyclerView);
rView.setHasFixedSize(true);
rView.setLayoutManager(layoutManager);
rView.setAdapter(productAdapter);
showProducts();
registerForContextMenu(rView);
}
make sure you initialize your adapter in your onCreate as I did and for your list do this in the onDataChange
`Product product = new Product(id, name, author, genre,
description, price, stock, image);
products.add(product);
productAdapter.notifyDataSetChanged();`
I want display pictures from firebase realtime database. (with Encryted image(String))
like Encrypted Image is "photo"
I run this app recyclerview didn't appear with error code
No adapter attached; skipping layout
ItemObject.java
public class ItemObject {
private String title;
private String Photo;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPhoto() {
return Photo;
}
public void setPhoto(String photo){
this.Photo=photo;
}
public ItemObject(String title, String photo) {
this.title = title;
this.Photo=photo;
}
public ItemObject() {}
}
Recyclerview adpater MyAdapter.java
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.RecyclerViewHolders> {
private Context context;
private ArrayList<ItemObject> mItem;
private AdapterView.OnItemClickListener mListener = null;
public class RecyclerViewHolders extends RecyclerView.ViewHolder
implements View.OnCreateContextMenuListener {
TextView title;
ImageView imageView;
// private CardView cardView;
public RecyclerViewHolders(#NonNull View itemView) {
super(itemView);
this.title = itemView.findViewById(R.id.title_listitem);
this.imageView = itemView.findViewById(R.id.photo_listitem);
//
itemView.setOnCreateContextMenuListener(this);
}
private final MenuItem.OnMenuItemClickListener onEditMenu = new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case 1001:
mItem.remove(getAdapterPosition());
notifyItemRemoved(getAdapterPosition());
notifyItemRangeChanged(getAdapterPosition(), mItem.size());
break;
}
return true;
}
};
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
MenuItem Delete = menu.add(Menu.NONE,1001,1,"삭제");
Delete.setOnMenuItemClickListener(onEditMenu);
}
}
public MyAdapter(ArrayList<ItemObject> item){
this.context = context;
this.mItem = item;
}
#NonNull
#Override
public RecyclerViewHolders onCreateViewHolder(#NonNull ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.listitem,viewGroup,false);
RecyclerViewHolders viewHolders=new RecyclerViewHolders(view);
return viewHolders;
}
#Override
public void onBindViewHolder(#NonNull RecyclerViewHolders holder, int position) {
/* Glide.with(context)
.load(mItem.get(position).getPhoto())
.into(holder.imageView);
*/
ItemObject itemObject = mItem.get(position);
String photo = itemObject.getPhoto();
holder.title.setTextSize(TypedValue.COMPLEX_UNIT_SP,10);
holder.title.setGravity(Gravity.CENTER);
holder.title.setText(itemObject.getTitle());
holder.imageView.setImageURI(Uri.parse(photo));
// Glide.with(this.context).load(mItem.get(position).getPhoto()).centerCrop().into(holder.imageView);
}
public void setmItem(ArrayList<ItemObject> mItem) {
this.mItem = mItem;
}
public void deleteItem(int position) {
mItem.remove(position);
notifyItemRemoved(position);
}
#Override
public int getItemCount() {
return mItem.size();
}
}
MainUpload.java
mRecyclerView = findViewById(R.id.recyclerview_main_list);
int numberOfColumns = 3;
GridLayoutManager mGridLayoutManager = new GridLayoutManager(getApplication(),numberOfColumns);
mRecyclerView.setLayoutManager(mGridLayoutManager);
mRecyclerView.setHasFixedSize(true);
reference = FirebaseDatabase.getInstance().getReference();
mItem = new ArrayList<>();
//clearAll();
loadPhoto();
DividerItemDecoration dividerItemDecoration=new DividerItemDecoration(mRecyclerView.getContext(),mGridLayoutManager.getOrientation());
mRecyclerView.addItemDecoration(dividerItemDecoration);
mRecyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), mRecyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
ItemObject itemObject = mItem.get(position);
Intent intent = new Intent(getApplicationContext(), DetailActivity.class);
intent.putExtra("title",itemObject.getTitle());
intent.putExtra("photo",itemObject.getPhoto());
startActivity(intent);
}
#Override
public void onLongClick(View view, int position) {
}
}));
function loadPhoto()
private void loadPhoto() {
FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
String key = FirebaseDatabase.getInstance().getInstance().getReference("users")
.child(currentUser.getUid()).child("Object").getKey();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("users")
.child(currentUser.getUid()).child("Object").child(key);
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
mRecyclerView = findViewById(R.id.recyclerview_main_list);
int numberOfColumns = 3;
GridLayoutManager mGridLayoutManager = new GridLayoutManager(getApplication(),numberOfColumns);
mRecyclerView.setLayoutManager(mGridLayoutManager);
mRecyclerView.setHasFixedSize(true);
ItemObject itemObject = new ItemObject();
//여기서 에러
String En1 = snapshot.child("photo").getValue().toString();
byte []En2 = En1.getBytes();
AESCoderAndriod aesCoderAndriod = new AESCoderAndriod();
try {
byte []Dn1 = aesCoderAndriod.decrypt(seed,En2);
Bitmap Dn2 = byteArrayToBitmap(Dn1);
Uri Dn3 = getImageUri(getApplicationContext(),Dn2);
itemObject.setPhoto(Dn3.toString());
itemObject.setTitle(snapshot.child("title").getValue().toString());
mItem.add(itemObject);
} catch (Exception e) {
e.printStackTrace();
}
// itemObject.setPhoto(snapshot.child("Photo").getValue().toString());
}
//myAdapter= new MyAdapter(getApplicationContext(),mItem);
// mRecyclerView.setAdapter(myAdapter);
myAdapter = new MyAdapter(mItem);
mRecyclerView.setAdapter(myAdapter);
myAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
what is the problem? I connect adapter and recyclerview, and set gridmanager.
You should set your adapter at first, Start with empty recycler view, when data loads you should notify your adapter about the change.
mRecyclerView.setLayoutManager(mGridLayoutManager);
mRecyclerView.setHasFixedSize(true);
mItem = new ArrayList<>();
myAdapter = new MyAdapter(mItem);
mRecyclerView.setAdapter(myAdapter);
loadPhoto();
You function already include notify data change method. You don't need to set new layout manager on data load method
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
ItemObject itemObject = new ItemObject();
//여기서 에러
String En1 = snapshot.child("photo").getValue().toString();
byte []En2 = En1.getBytes();
AESCoderAndriod aesCoderAndriod = new AESCoderAndriod();
try {
byte []Dn1 = aesCoderAndriod.decrypt(seed,En2);
Bitmap Dn2 = byteArrayToBitmap(Dn1);
Uri Dn3 = getImageUri(getApplicationContext(),Dn2);
itemObject.setPhoto(Dn3.toString());
itemObject.setTitle(snapshot.child("title").getValue().toString());
mItem.add(itemObject);
} catch (Exception e) {
e.printStackTrace();
}
// itemObject.setPhoto(snapshot.child("Photo").getValue().toString());
}
myAdapter.notifyDataSetChanged();
}
I have added cart image in my Adapter class but whenever I click on the button always get the last element from the list. Here is my adapter class and activity class.
Details are perfectly fetched from firebase and Log file showing list of menu.
Here is my MenuAdapter.java class.
public class MenuAdapter extends RecyclerView.Adapter<MenuAdapter.MenuViewHolder> {
private Context mCtx;
private List<Menu> menuList;
private ItemClickEvent itemclick;
public MenuAdapter(Context mCtx, List<Menu> menuList, ItemClickEvent itemclick) {
this.mCtx = mCtx;
this.menuList = menuList;
this.itemclick = itemclick;
}
#NonNull
#Override
public MenuViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i)
{
View view = LayoutInflater.from(mCtx).inflate(R.layout.menu_list, viewGroup, false);
return new MenuViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final MenuViewHolder menuViewHolder, final int i) {
final Menu menu = menuList.get(i);
menuViewHolder.itemName.setText(menu.itemName);
menuViewHolder.itemPrice.setText(menu.itemPrice);
menuViewHolder.addCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
itemclick.imageClicked(menu);
}
});
}
#Override
public int getItemCount() {
return menuList.size();
}
public class MenuViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView itemName, itemPrice;
#SuppressLint("StaticFieldLeak")
ImageView addCart;
MenuViewHolder(#NonNull View itemView) {
super(itemView);
itemName = itemView.findViewById(R.id.itemName);
itemPrice = itemView.findViewById(R.id.itemPrice);
addCart = itemView.findViewById(R.id.menuAddCart);
//addCart.setOnClickListener(this);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
}
}
}
and this MenuActivity.java class
public class MenuActivity extends AppCompatActivity implements ItemClickEvent
{
private ActionBar toolbar;
List<Menu> menuList;
RecyclerView recyclerView;
MenuAdapter adapter;
DatabaseReference databaseReference;
ProgressBar progressBar;
Menu menu;
int foodId = 1;
int cat;
String id,itemName, itemPrice;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
Intent intent = getIntent();
final String category = intent.getStringExtra("cat_id");
final String catName = intent.getStringExtra("cat_name");
toolbar = getSupportActionBar();
toolbar.setTitle(catName);
cat = Integer.parseInt(category) - 1;
menuList = new ArrayList<>();
recyclerView = findViewById(R.id.menu_recycler);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MenuAdapter(this, menuList,this);
recyclerView.setAdapter(adapter);
ImageView addTCart = findViewById(R.id.menuAddCart);
progressBar = findViewById(R.id.progressBarLoading);
databaseReference = FirebaseDatabase.getInstance().getReference("foods/" + cat + "/menu-items");
// fetchMenu(category);
progressBar.setVisibility(View.VISIBLE);
databaseReference.addListenerForSingleValueEvent(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
progressBar.setVisibility(View.GONE);
if (dataSnapshot.exists()) {
for (DataSnapshot wallpaperSnapshot : dataSnapshot.getChildren()) {
id = wallpaperSnapshot.getKey();
itemName = wallpaperSnapshot.child("name").getValue(String.class);
itemPrice = wallpaperSnapshot.child("price").getValue(String.class);
menu = new Menu(id, itemName, itemPrice, category);
menuList.add(menu);
Log.d("FOOD-DETAIL", String.valueOf(menu));
}
adapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void imageClicked(Menu m) {
new Database(getApplicationContext()).addToCart(new Order(
Integer.parseInt(id),
menu.getItemName(),
"1",
menu.getItemPrice()
));
foodId += 1;
Toast.makeText(getBaseContext(), itemName+" added to cart", Toast.LENGTH_SHORT).show();
}
#Override
public void viewClicked() {
}
}
Hello try making these changes in imageClicked() in MenuActivity
#Override
public void imageClicked(Menu m) {
new Database(getApplicationContext()).addToCart(new Order(
m.getId(),
m.getItemName(),
"1",
m.getItemPrice()
));
foodId += 1;
Toast.makeText(getBaseContext(), itemName+" added to cart", Toast.LENGTH_SHORT).show();
}
There should be more efficient way to set listener. Just set that listener (same way as it is now) in constructor of MenuViewHolder and assign to this. And in method onClick - check R.id of view and if it is addCart instead of calling itemclick.imageClicked(menu) just call item.click.imageClicked(getAdapterPosition())
This because onBindViewHolder() is calling multiple times and you will still create new listener. But in constructor you create that listener only if you need new MenuViewHolder and use the actual position of adapter.
I created a recyclerview that takes data from Firebase. I have two arrays that are sent to the adapter to be used in the items. I've implemented a search filter. This works for the first array, but the second one is always in the starting position. How can I get the second array in the same position as the first filter? Thank you
MainActivity
public class FriendActivity3 extends AppCompatActivity
//implements FriendHoldAdapter3.ItemClickListener{
FriendHoldAdapter3 adapter;
RecyclerView recyclerView;
ArrayList<FriendItem> username;
ArrayList<String> uid, url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_friend2);
SearchView search = (SearchView) findViewById(R.id.ciao);
recyclerView = (RecyclerView) findViewById(R.id.friend_list2);
//recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
final DatabaseReference mPostReference = FirebaseDatabase.getInstance().getReference().child("user-profile");
mPostReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
username = new ArrayList<>();
uid = new ArrayList<String>();
url = new ArrayList<String>();
for (DataSnapshot data : dataSnapshot.getChildren()){
final FriendItem friendItem = data.getValue(FriendItem.class);
final String friendItem2 = data.getKey();
username.add(friendItem);
uid.add(friendItem2);
adapter = new FriendHoldAdapter3(getApplicationContext(), username, uid, url);
//adapter.setClickListener(FriendActivity3.this);
recyclerView.setAdapter(adapter);
/**
adapter = new FriendHoldAdapter2(FriendActivity2.this, username, uid);
adapter.setClickListener(FriendActivity2.this);
recyclerView.setAdapter(adapter);
**/
final List<FriendItem> filteredModelList = filter(username, " ");
adapter.setFilter(filteredModelList);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}});
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
if (newText.equals("")){
newText = " ";
}
if (newText.equals("View All")){
newText = "";
}
final List<FriendItem> filteredModelList = filter(username, newText);
adapter.setFilter(filteredModelList);
return true;
}
});
private List<FriendItem> filter(List<FriendItem> models, String query) {
query = query.toLowerCase();final List<FriendItem> filteredModelList = new ArrayList<>();
for (FriendItem model : models) {
final String text = model.username.toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}}
Adapter
public class FriendHoldAdapter3 extends RecyclerView.Adapter<FriendHoldAdapter3.ViewHolder> {
private List<FriendItem> mData_username = Collections.emptyList();
private List<String> mData_uid = Collections.emptyList();
private List<String> mData_url = Collections.emptyList();
private LayoutInflater mInflater;
private ItemClickListener mClickListener;
// data is passed into the constructor
public FriendHoldAdapter3(Context context, List<FriendItem> data_username, List<String> data_uid, List<String> data_url) {
this.mInflater = LayoutInflater.from(context);
this.mData_username = data_username;
this.mData_uid = data_uid;
this.mData_url = data_url;
}
// inflates the row layout from xml when needed
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.friend_item, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
// binds the data to the textview in each row
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
FriendItem username = mData_username.get(position);
String uid = mData_uid.get(position);
holder.myTextView.setText(username.username);
holder.uid_txt.setText(uid);
}
// total number of rows
#Override
public int getItemCount() {
return mData_username.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView myTextView, uid_txt;
public ViewHolder(final View itemView) {
super(itemView);
myTextView = (TextView) itemView.findViewById(R.id.friend_item_name);
uid_txt = (TextView) itemView.findViewById(R.id.friend_item_uid);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(itemView.getContext(),mData_uid.get(getAdapterPosition()), Toast.LENGTH_SHORT).show();
if (uid_txt.getText().toString()!=null | !uid_txt.getText().toString().equals("") ){
Intent intent = new Intent(itemView.getContext(), AccountPubblic.class);
//MANDARE TESTO A AccountPubblic
intent.putExtra(AccountPubblic.EXTRA_UID, uid_txt.getText().toString());
itemView.getContext().startActivity(intent);
}
}
});
}
#Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
// convenience method for getting data at click position
public FriendItem getItem(int id) {
return mData_username.get(id);
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
// allows clicks events to be caught
public void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
public void setFilter(List<FriendItem> countryModels) {
mData_username = new ArrayList<>();
mData_username.addAll(countryModels);
notifyDataSetChanged();
}}
I'm trying to display the data from my Firebase but it won't display to my recyclerView. I don't know what was wrong.
I'm also trying to find some tutorials or the same question from stackoverflow but I don't get it. Still don't show the data from Firebase.
HistoryActivity.class
public class HistoryActivity extends AppCompatActivity {
String name, route;
int earnings, time, distance, totalPassenger, tripCount;
private Firebase ref;
private RecyclerView recycler;
private RecyclerViewAdapter adapter;
List<History> historyList;
History history;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
Firebase.setAndroidContext(this);
recycler = (RecyclerView) findViewById(R.id.recyclerview);
historyList = fillData();
recycler.setLayoutManager(new LinearLayoutManager(this));
}
public List<History> fillData() {
historyList = new ArrayList<>();
ref = new Firebase(Config.FIREBASE_URL_HISTORY_DRIVER);
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Toast.makeText(HistoryActivity.this, snapshot.getValue()+"", Toast.LENGTH_SHORT).show();
name = snapshot.child("driverName").getValue().toString().trim();
route = snapshot.child("destination").getValue().toString().trim();
earnings = Integer.valueOf(snapshot.child("earnings").getValue().toString().trim());
time = Integer.valueOf(snapshot.child("time").getValue().toString().trim());
distance = Integer.valueOf(snapshot.child("distanceTravelled").getValue().toString().trim());
totalPassenger = Integer.valueOf(snapshot.child("totalPassenger").getValue().toString().trim());
tripCount = Integer.valueOf(snapshot.child("tripCount").getValue().toString().trim());
historyList.add(new History(name, route, earnings, time, distance, totalPassenger, tripCount));
}
Toast.makeText(HistoryActivity.this, historyList.size()+":size", Toast.LENGTH_LONG).show();
adapter = new RecyclerViewAdapter(historyList);
recycler.setAdapter(adapter);
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
return historyList;
}
}
RecyclerViewAdapter
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.HistoryViewHolder> {
List<History> historyList;
Context context;
public RecyclerViewAdapter(List<History> historyList) {
this.historyList = historyList;
}
#Override
public HistoryViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//inflate the layout, initialize the View Holder
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_layout, parent, false);
HistoryViewHolder holder = new HistoryViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(RecyclerViewAdapter.HistoryViewHolder holder, int position) {
holder.driversName.setText(historyList.get(position).getDriversName());
holder.route.setText(historyList.get(position).getRoute());
holder.totalEarnings.setText(historyList.get(position).getEarnings());
holder.time.setText(historyList.get(position).getTime());
holder.distance.setText(historyList.get(position).getDistance());
holder.totalPassenger.setText(historyList.get(position).getTotalPassenger());
holder.tripCount.setText(historyList.get(position).getTripCount());
animate(holder);
}
#Override
public int getItemCount() {
return historyList.size();
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
public void animate(RecyclerView.ViewHolder viewHolder) {
final Animation animAnticipateOvershoot = AnimationUtils.loadAnimation(context, R.anim.bounce_interpolator);
viewHolder.itemView.setAnimation(animAnticipateOvershoot);
}
public static class HistoryViewHolder extends RecyclerView.ViewHolder {
CardView cardView;
EditText driversName;
EditText route;
EditText totalEarnings;
EditText time;
EditText distance;
EditText totalPassenger;
EditText tripCount;
public HistoryViewHolder(View itemView) {
super(itemView);
cardView = (CardView) itemView.findViewById(R.id.cardView);
driversName = (EditText) itemView.findViewById(R.id.edtDriversName);
route = (EditText) itemView.findViewById(R.id.edtRoute);
totalEarnings = (EditText) itemView.findViewById(R.id.edtEarning);
time = (EditText) itemView.findViewById(R.id.edtTime);
distance = (EditText) itemView.findViewById(R.id.edtDistance);
totalPassenger = (EditText) itemView.findViewById(R.id.edtTotalPass);
tripCount = (EditText) itemView.findViewById(R.id.edtTripCount);
}
}
}
History(pojo)
public class History {
private String username;
private String driversName;
private String route;
private int earnings;
private int time;
private int distance;
private int totalPassenger;
private int tripCount;
public History(String driversName, String route, int earnings, int time, int distance, int totalPassenger, int tripCount) {
this.driversName = driversName;
this.route = route;
this.earnings = earnings;
this.time = time;
this.distance = distance;
this.totalPassenger = totalPassenger;
this.tripCount = tripCount;
}
You need to set layout before setting adapter like this:
recycler = (RecyclerView) findViewById(R.id.recyclerview);
recycler.setLayoutManager(new LinearLayoutManager(this));
historyList = fillData();