No adapter attached; skipping layout (Recyclerview) - android

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();
}

Related

RecyclerView: No adapter attached; skipping layout (can't find issue)

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();`

Recycler View not updating messages from Firebase Database: Android Studio

When sending messages to firebase recycler view reading them but recycler view not updating instantly....i have tried notifyDataSetChanged() but not working.................................................................................................................................................................
MessagingActivity.java
public class MessagingActivity extends AppCompatActivity {
RecyclerView recyclerView;
ImageView ivBack, ivSend;
EditText etTypeMessage;
TextView tvName;
String Receiverphone, image, name;
CircleImageView civProfile;
DatabaseReference reference;
MessagingAdapter adapter;
ArrayList<MessagingBinding> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_messaging);
recyclerView = findViewById(R.id.rv_messagingActivity);
ivBack = findViewById(R.id.ivBack_messagingActivity);
etTypeMessage = findViewById(R.id.etTypeMessage_activityMessaging);
tvName = findViewById(R.id.tvName_activityMessaging);
civProfile = findViewById(R.id.civProfile_messagingActivity);
ivSend = findViewById(R.id.ivSend_activityMessaging);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
image = getIntent().getStringExtra("image");
name = getIntent().getStringExtra("name");
Receiverphone = getIntent().getStringExtra("phone");
tvName.setText(name);
Picasso.get().load(image).into(civProfile);
reference = FirebaseDatabase.getInstance().getReference().child("Users");
ivSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Messages messages = new Messages(etTypeMessage.getText().toString(), name, image, Singleton.obj.phone, Receiverphone);
reference.child("messages").push().setValue(messages);
etTypeMessage.setText("");
adapter.notifyDataSetChanged();
}
});
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MessagingActivity.this);
linearLayoutManager.setStackFromEnd(true);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(linearLayoutManager);
list = new ArrayList<>();
reference.child("messages").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
Messages messages = dataSnapshot.getValue(Messages.class);
if (messages.getSenderphone().equals(Singleton.obj.phone) && messages.getReceiverPhone().equals(Receiverphone)) {
list.add(messages);
}
}
adapter = new MessagingAdapter(list);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
ivBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MessagingActivity.this, MainActivity.class);
startActivity(intent);
}
});
}
}
MessagingAdapter.javastrong text
public class MessagingAdapter extends RecyclerView.Adapter {
private ArrayList<MessagingBinding> bindingList;
public MessagingAdapter(ArrayList<MessagingBinding> bindingList) {
this.bindingList = bindingList;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
switch (viewType) {
case (MessagingBinding.TYPE_SENDER):
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_sendermessaging, parent, false);
return new SenderViewHolder(view);
default:
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_receivermessaging, parent, false);
return new ReceiverViewHodler(view);
}
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
switch (getItemViewType(position)) {
case (MessagingBinding.TYPE_SENDER):
((SenderViewHolder) holder).bindView(position);
break;
case (MessagingBinding.TYPE_RECEIVER):
((ReceiverViewHodler)holder).bindView(position);
break;
}
}
#Override
public int getItemCount() {
if (bindingList == null) {
return 0;
} else {
return bindingList.size();
}
}
#Override
public int getItemViewType(int position) {
return bindingList.get(position).getType();
}
class SenderViewHolder extends RecyclerView.ViewHolder {
TextView tvSender;
ImageView ivSender;
public SenderViewHolder(#NonNull View itemView) {
super(itemView);
tvSender = itemView.findViewById(R.id.tvSender_listItemsMessaging);
ivSender = itemView.findViewById(R.id.ivSender_listItemMessaging);
}
void bindView(int position) {
SenderMessaging sender = (SenderMessaging) bindingList.get(position);
tvSender.setText(sender.getTvSenderMsg());
ivSender.setImageResource(sender.getImg());
}
}
//-------------------------------ReceiverViewHolder----------------------------------
class ReceiverViewHodler extends RecyclerView.ViewHolder {
TextView tvReceiver;
public ReceiverViewHodler(#NonNull View itemView) {
super(itemView);
tvReceiver = itemView.findViewById(R.id.tvReceiver_listItemsMessaging);
}
void bindView(int position) {
Messages receiver = (Messages) bindingList.get(position);
tvReceiver.setText(receiver.getMessage());
}
}
}
From your code, your messages should be visible when firebase notify you with changes in your db.
Please, try next code:
MessagingActivity
public class MessagingActivity extends AppCompatActivity {
RecyclerView recyclerView;
ImageView ivBack, ivSend;
EditText etTypeMessage;
TextView tvName;
String Receiverphone, image, name;
CircleImageView civProfile;
DatabaseReference reference;
MessagingAdapter adapter;
ArrayList<MessagingBinding> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_messaging);
recyclerView = findViewById(R.id.rv_messagingActivity);
ivBack = findViewById(R.id.ivBack_messagingActivity);
etTypeMessage = findViewById(R.id.etTypeMessage_activityMessaging);
tvName = findViewById(R.id.tvName_activityMessaging);
civProfile = findViewById(R.id.civProfile_messagingActivity);
ivSend = findViewById(R.id.ivSend_activityMessaging);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
image = getIntent().getStringExtra("image");
name = getIntent().getStringExtra("name");
Receiverphone = getIntent().getStringExtra("phone");
tvName.setText(name);
Picasso.get().load(image).into(civProfile);
reference = FirebaseDatabase.getInstance().getReference().child("Users");
ivSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Messages messages = new Messages(etTypeMessage.getText().toString(), name, image, Singleton.obj.phone, Receiverphone);
reference.child("messages").push().setValue(messages);
etTypeMessage.setText("");
}
});
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MessagingActivity.this);
linearLayoutManager.setStackFromEnd(true);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(linearLayoutManager);
list = new ArrayList<>();
reference.child("messages").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
Messages messages = dataSnapshot.getValue(Messages.class);
if (messages.getSenderphone().equals(Singleton.obj.phone) && messages.getReceiverPhone().equals(Receiverphone)) {
list.add(messages);
}
}
adapter = new MessagingAdapter(list);
recyclerView.setAdapter(adapter);
adapter.updateList(list);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
ivBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MessagingActivity.this, MainActivity.class);
startActivity(intent);
}
});
}
And the Adapter:
public class MessagingAdapter extends RecyclerView.Adapter {
private ArrayList<MessagingBinding> bindingList;
public MessagingAdapter(ArrayList<MessagingBinding> bindingList) {
this.bindingList = bindingList;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
switch (viewType) {
case (MessagingBinding.TYPE_SENDER):
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_sendermessaging, parent, false);
return new SenderViewHolder(view);
default:
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_receivermessaging, parent, false);
return new ReceiverViewHodler(view);
}
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
switch (getItemViewType(position)) {
case (MessagingBinding.TYPE_SENDER):
((SenderViewHolder) holder).bindView(position);
break;
case (MessagingBinding.TYPE_RECEIVER):
((ReceiverViewHodler)holder).bindView(position);
break;
}
}
#Override
public int getItemCount() {
if (bindingList == null) {
return 0;
} else {
return bindingList.size();
}
}
public void updateList(ArrayList<MessagingBinding> messages){
this.bindingList = messages;
this.notifyDataSetChanged();
}
#Override
public int getItemViewType(int position) {
return bindingList.get(position).getType();
}
class SenderViewHolder extends RecyclerView.ViewHolder {
TextView tvSender;
ImageView ivSender;
public SenderViewHolder(#NonNull View itemView) {
super(itemView);
tvSender = itemView.findViewById(R.id.tvSender_listItemsMessaging);
ivSender = itemView.findViewById(R.id.ivSender_listItemMessaging);
}
void bindView(int position) {
SenderMessaging sender = (SenderMessaging) bindingList.get(position);
tvSender.setText(sender.getTvSenderMsg());
ivSender.setImageResource(sender.getImg());
}
}
//-------------------------------ReceiverViewHolder----------------------------------
class ReceiverViewHodler extends RecyclerView.ViewHolder {
TextView tvReceiver;
public ReceiverViewHodler(#NonNull View itemView) {
super(itemView);
tvReceiver = itemView.findViewById(R.id.tvReceiver_listItemsMessaging);
}
void bindView(int position) {
Messages receiver = (Messages) bindingList.get(position);
tvReceiver.setText(receiver.getMessage());
}
}
}

How do I add an OnClickListener And An Animation In A RecyclerView?

Okay so I have RecyclerView in which I retrieve some data from Firebase realtime database and I have a SearchView which filters my database. Now I want two things
I want an OnClicListener in my activity with which I could open a fragment by clicking on of the items.
I want to apply animation to my RecyclerView every time I scroll down.
Note: The OnClickListener should also work after filtering the data.
So far I am unable to achieve this. Here is my code
Adapter Class -> AdapterClass.java
public class AdapterClass extends RecyclerView.Adapter<AdapterClass.MyViewHolder>{
ArrayList<Deal> list;
public AdapterClass(ArrayList<Deal> list)
{
this.list = list;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_holder,viewGroup,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, final int i) {
myViewHolder.id.setText(list.get(i).getDealId());
myViewHolder.desc.setText(list.get(i).getDealDisc());
}
#Override
public int getItemCount() {
return list.size();
}
static class MyViewHolder extends RecyclerView.ViewHolder{
TextView id,desc;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
id= itemView.findViewById(R.id.dealId);
desc=itemView.findViewById(R.id.description);
}
}
}
Model Class -> Deal.java
public class Deal {
private String dealDisc;
private String dealId;
private String dealImage;
private String price;
public Deal() {
}
public Deal(String dealDisc, String dealId, String dealImage, String price) {
this.dealDisc = dealDisc;
this.dealId = dealId;
this.dealImage = dealImage;
this.price = price;
}
public String getDealDisc() {
return dealDisc;
}
public void setDealDisc(String dealDisc) {
this.dealDisc = dealDisc;
}
public String getDealId() {
return dealId;
}
public void setDealId(String dealId) {
this.dealId = dealId;
}
public String getDealImage() {
return dealImage;
}
public void setDealImage(String dealImage) {
this.dealImage = dealImage;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
Main Activity -> MainActivity.java
public class MainActivity extends AppCompatActivity {
DatabaseReference ref;
ArrayList<Deal> list;
RecyclerView recyclerView;
SearchView searchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ref= FirebaseDatabase.getInstance().getReference().child("rana");
recyclerView = findViewById(R.id.rv);
searchView=findViewById(R.id.searchView);
}
#Override
protected void onStart() {
super.onStart();
if (ref != null)
{
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists())
{
list = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren())
{
list.add(ds.getValue(Deal.class));
}
AdapterClass adapterClass = new AdapterClass(list);
recyclerView.setAdapter(adapterClass);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(MainActivity.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<Deal> myList = new ArrayList<>();
for (Deal object : list)
{
if (object.getDealDisc().toLowerCase().contains(str.toLowerCase()) || object.getDealId().toLowerCase().contains(str.toLowerCase()))
{
myList.add(object);
}
}
AdapterClass adapterClass = new AdapterClass(myList);
recyclerView.setAdapter(adapterClass);
}
}
myViewHolder.id.setonclickListener()

RecyclerView onClick not working on search items

I have implemented a search function on my application and it displays the results however the results can not be clicked. When not in search the onClick method works fine. Here is the code for my main class where the search takes place
MainActivity.java
public class MainActivity extends AppCompatActivity implements
RecyclerViewAdapter.OnItemClickListener {
private RecyclerView mRecyclerView;
private RecyclerViewAdapter mAdapter;
private DatabaseReference mDatabaseRef;
private List<Buildings> mUploads;
private FirebaseAuth mAuth;
private FirebaseUser mCurrentUser;
private FirebaseStorage mStorage;
private ValueEventListener mDBListener;
private EditText msearch;
ArrayList<Buildings> arrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
mCurrentUser = mAuth.getCurrentUser();
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mUploads = new ArrayList<>();
mStorage = FirebaseStorage.getInstance();
mDatabaseRef =
FirebaseDatabase.getInstance().getReference("Buildings");
mAdapter = new RecyclerViewAdapter(MainActivity.this, mUploads);
mRecyclerView.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(MainActivity.this);
msearch = findViewById(R.id.search);
arrayList = new ArrayList<>();
msearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int
count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
#Override
public void afterTextChanged(Editable s) {
if(!s.toString().isEmpty())
{
search(s.toString());
}
else{
search("");
}
}
});
//GET DATA FROM FIREBASE!!
mDBListener = mDatabaseRef.addValueEventListener(new
ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mUploads.clear();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Buildings upload = postSnapshot.getValue(Buildings.class);
upload.setKey(postSnapshot.getKey());
mUploads.add(upload);
}
mAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(MainActivity.this, databaseError.getMessage(),
Toast.LENGTH_SHORT).show();
}
});
} //end of on create
private void search(String s) {
Query query = mDatabaseRef.orderByChild("name")
.startAt(s).endAt(s + "\uf8ff");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChildren()){
arrayList.clear();
for(DataSnapshot dss: dataSnapshot.getChildren()){
final Buildings buildings = dss.getValue(Buildings.class);
arrayList.add(buildings);
}
RecyclerViewAdapter myAdapter = new RecyclerViewAdapter(getApplicationContext(),arrayList);
mRecyclerView.setAdapter(myAdapter);
myAdapter.notifyDataSetChanged();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onItemClick(int position) {
Buildings selectedItem = mUploads.get(position);
final String name = selectedItem.getName();
final String address = selectedItem.getAddress();
final String image_url = selectedItem.getImage_url();
final double longt = selectedItem.getLongitude();
final double lat = selectedItem.getLatitude();
final String uid = selectedItem.getUserID();
final String desc = selectedItem.getDescription();
final String categ = selectedItem.getCategorie();
Intent mainIntent = new Intent(MainActivity.this, ProfileActivity2.class);
mainIntent.putExtra("b_name", name);
mainIntent.putExtra("b_address", address);
mainIntent.putExtra("b_image_url", image_url);
mainIntent.putExtra("b_userId", uid);
mainIntent.putExtra("b_desc", desc);
mainIntent.putExtra("b_categ", categ);
Bundle b = new Bundle();
b.putDouble("longt", longt);
b.putDouble("lat", lat);
mainIntent.putExtras(b);
startActivity(mainIntent);
finish();
}
RecyclerViewAdapter.java
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ImageViewHolder> {
private Context mContext;
private List<Buildings> mUploads;
private OnItemClickListener mListener;
private FirebaseAuth mAuth;
private FirebaseUser mCurrentUser;
private boolean checkUid;
public RecyclerViewAdapter(Context context, List<Buildings> uploads) {
mContext = context;
mUploads = uploads;
}
#Override
public ImageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.buildings_row_item, parent, false);
return new ImageViewHolder(v);
}
#Override
public void onBindViewHolder(ImageViewHolder holder, int position) {
Buildings uploadCurrent = mUploads.get(position);
holder.textViewName.setText(uploadCurrent.getName());
holder.textViewAddress.setText(uploadCurrent.getAddress());
Glide.with(mContext).load(mUploads.get(position).getImage_url()).into(holder.imageView);
}
#Override
public int getItemCount() {
return mUploads.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,
View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener {
public TextView textViewName;
public ImageView imageView;
public TextView textViewAddress;
LinearLayout view_container;
public ImageViewHolder(View itemView) {
super(itemView);
textViewName = itemView.findViewById(R.id.building_name);
imageView = itemView.findViewById(R.id.thumbnail);
view_container = itemView.findViewById(R.id.container);
textViewAddress = itemView.findViewById(R.id.address);
itemView.setOnClickListener(this);
itemView.setOnCreateContextMenuListener(this);
}
#Override
public boolean onMenuItemClick(MenuItem item) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
switch (item.getItemId()) {
case 1:
mListener.onDeleteClick(position);
return true;
}
}
}
return false;
}
#Override
public void onClick(View v) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(position);
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
if(checkUid =true && mCurrentUser != null){
MenuItem delete = menu.add(Menu.NONE, 1, 1, "Delete");
delete.setOnMenuItemClickListener(this);
}
else{
//do nothing
}
}
}
public interface OnItemClickListener {
void onItemClick(int position);
void onDeleteClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
}
Should I be adding something to my search function?
You are creating new adapter on reponse of your query, which isn't having active interface attached. So instead of creating new adapter, just update the data list and notify adapter.
Refer below code.
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChildren()){
arrayList.clear();
for(DataSnapshot dss: dataSnapshot.getChildren()){
final Buildings buildings = dss.getValue(Buildings.class);
arrayList.add(buildings);
}
// Remove below two lines,
// It is not needed as we only need to notify adapter about the data change.
// RecyclerViewAdapter myAdapter = new RecyclerViewAdapter(getApplicationContext(),arrayList);
// mRecyclerView.setAdapter(myAdapter);
myAdapter.notifyDataSetChanged();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
In search method, you create a new adapter but not setting its onItemClickListener.
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChildren()){
arrayList.clear();
for(DataSnapshot dss: dataSnapshot.getChildren()){
final Buildings buildings = dss.getValue(Buildings.class);
arrayList.add(buildings);
}
RecyclerViewAdapter myAdapter = new RecyclerViewAdapter(getApplicationContext(),arrayList);
mRecyclerView.setAdapter(myAdapter);
myAdapter.notifyDataSetChanged();
}
}
Separate the setData and construct method for adapter, then you don't need to create new adapter every search. Or just set mAdapter.setOnItemClickListener for it.

wrong positions of two arrays after filter

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();
}}

Categories

Resources