RecyclerView onClick not working on search items - android

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.

Related

No adapter attached; skipping layout (Recyclerview)

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

Not printing the position of recyclerView in logcat

I'm trying to print the position of RecyclerView in logcat when I click on the list of recyclerView, but it's not printing anything. Actually in this app, if I click on a position of the recyclerview, that should take me to new activity and grab all the details of that position on which I clicked.
Here is my ImageAdapter.java class
public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ImageViewHolder> {
private Context mContext;
private List<UserDetails> mUploads;
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
public ImageAdapter(Context context, List<UserDetails> uploads) {
mContext = context;
mUploads = uploads;
}
#NonNull
#Override
public ImageViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(mContext).inflate(R.layout.user_display, viewGroup, false);
return new ImageViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ImageViewHolder imageViewHolder, int i) {
UserDetails currentItem = mUploads.get(i);
UserDetails userDetails = mUploads.get(i);
imageViewHolder.requestId.setText("Request Id : " + userDetails.getMobileNumber());
imageViewHolder.customerName.setText(userDetails.getName());
imageViewHolder.customerMobile.setText("Mobile : " + userDetails.getMobileNumber());
imageViewHolder.customerAddress.setText(userDetails.getAddress());
}
#Override
public int getItemCount() {
return mUploads.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder {
public TextView requestId, customerName, customerAddress, customerMobile, serviceType, date;
public ImageViewHolder(#NonNull View itemView) {
super(itemView);
requestId = itemView.findViewById(R.id.requestId);
customerName = itemView.findViewById(R.id.customerName);
customerAddress = itemView.findViewById(R.id.customerAddress);
customerMobile = itemView.findViewById(R.id.customerMobile);
serviceType = itemView.findViewById(R.id.serviceType);
date = itemView.findViewById(R.id.date);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(position);
}
}
}
});
}
}
}
and here is the recyclerView class
public class requestList extends AppCompatActivity implements ImageAdapter.OnItemClickListener {
RecyclerView recyclerView;
DatabaseReference databaseReference;
List<UserDetails> downloadDataArray;
ImageAdapter adapter;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_request_list);
progressBar = findViewById(R.id.progressBar);
Toolbar toolbar = findViewById(R.id.roServiceToolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Requests");
toolbar.setNavigationIcon(R.drawable.back);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(requestList.this, customerRequests.class));
}
});
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
downloadDataArray = new ArrayList<>();
databaseReference = FirebaseDatabase.getInstance().getReference("Service Request/RO Service");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
downloadDataArray.clear();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
UserDetails userDetails = postSnapshot.getValue(UserDetails.class);
downloadDataArray.add(userDetails);
}
adapter = new ImageAdapter(requestList.this, downloadDataArray);
getSupportActionBar().setTitle("Requests" + "(" +adapter.getItemCount()+ ")");
recyclerView.setAdapter(adapter);
progressBar.setVisibility(View.INVISIBLE);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onItemClick(int position) {
Log.i("Position", String.valueOf(position));
}
}
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
//print log message
}
}
}
});
Because you are not assigning the value of mListener. Add this line after initialize adapter object.
adapter.setOnItemClickListener(this)

How to handle RecyclerView positions in a correct way?

I am using a recyclerview and inside its adapter I have another recyclerview.
How to prevent item change and item refresh when an item is updated.
This is creating visual glitches and wrong positioning of the items
I have tried to read directly from a database reference on the current position of the holder.
Result: https://media.giphy.com/media/j6TpXZRE6e44cMZVIP/giphy.gif
public class CommentsAdapter extends RecyclerView.Adapter<CommentsAdapter.ViewHolder>{
private Context mContext;
private List<Comments> mComments;
private List<Replies> allReplies;
public CommentsAdapter(Context mContext, List<Comments> mComments, List<Replies> allReplies )
{
this.mContext = mContext;
this.mComments = mComments;
this.allReplies = allReplies;
}
#NonNull
#Override
public CommentsAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(mContext).inflate(R.layout.all_comments_layout, viewGroup, false);
return new CommentsAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position)
{
final Comments comments = mComments.get(position);
holder.like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CommentUps.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
{
if (dataSnapshot.child(PostKey).child(com_uid).hasChild(currentUserID)) {
CommentUps.child(PostKey).child(com_uid).child(currentUserID).removeValue();
CommentsRef.child(PostKey).child(com_uid).child("likes").setValue(comments.getLikes() - 1);
} else {
CommentUps.child(PostKey).child(com_uid).child(currentUserID).setValue(true);
CommentsRef.child(PostKey).child(com_uid).child("likes").setValue(comments.getLikes() + 1);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
});
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Replies");
//reference.orderByChild("pLikes")
reference.orderByChild(com_uid).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
holder.repliesList.clear();
for (DataSnapshot snapshot : dataSnapshot.child(PostKey).child(com_uid).getChildren())
{
Replies replies = snapshot.getValue(Replies.class);
//final String com = comment.toString();
// Log.d(new String("Comments"), com);
//for (String id : followingList)
if (replies.getComment_uid().equals(com_uid))
{
holder.repliesList.add(replies);
}
}
holder.repliesAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public int getItemCount() {
return mComments.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageButton like
List<Replies> repliesList;
RepliesAdapter repliesAdapter;
public ViewHolder(View itemView) {
super(itemView);
like = itemView.findViewById(R.id.comment_like_button);
repliesRecycler = itemView.findViewById(R.id.all_replies_recycler);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
repliesRecycler.setLayoutManager(linearLayoutManager);
repliesRecycler.setHasFixedSize(true);
repliesList = new ArrayList<>();
repliesAdapter = new RepliesAdapter(mContext, repliesList);
repliesRecycler.setAdapter(repliesAdapter);
repliesAdapter.notifyDataSetChanged();
}
// Second Method - Same Result
private void displayReplies(final String com_uid ,final String PostKey, final boolean locked) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Replies");
reference.child(PostKey).child(com_uid).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
repliesList.clear();
if (dataSnapshot.exists()) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
final Replies replies = snapshot.getValue(Replies.class);
if (replies.getComment_uid().equals(com_uid)) {
repliesList.add(replies);
repliesAdapter.notifyDataSetChanged();
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
My replies adapter:
public class RepliesAdapter extends RecyclerView.Adapter<RepliesAdapter.ViewHolder>
{
public Context mContext;
public List<Replies> mReplies;
public RepliesAdapter(Context mContext, List<Replies> mReplies)
{
this.mContext = mContext;
this.mReplies = mReplies;
}
#NonNull
#Override
public RepliesAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(mContext).inflate(R.layout.all_replies_layout, viewGroup, false);
mAuth = FirebaseAuth.getInstance();
return new RepliesAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position)
{
final Replies replies = mReplies.get(position);
holder.myUserName.setText(replies.getUsername());
holder.myComment.setText(replies.getReply());
holder.myTime.setText(replies.getTime());
}
#Override
public int getItemCount() {
return mReplies.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView myUserName, myComment,myTime;
public ViewHolder(View itemView) {
super(itemView);
myUserName = itemView.findViewById(R.id.reply_username);
myComment = itemView.findViewById(R.id.reply_text);
myTime = itemView.findViewById(R.id.reply_time);
}
}

Search bar using RecyclerView with Firebase(OnClick)

I am trying to build a firebase application where a user could search for their client and then click on the search result, will redirect to client profile activity with their data were passed on. I am using firebase realtime database. I can't seem to find a way to pass the data to from the search list when I click on the list. Basically, I am having trouble passing the data via OnClick after the search result
Search_lecturer class
public class Search_lecturer extends AppCompatActivity {
EditText search_lecturer;
RecyclerView recyclerView;
DatabaseReference databaseReference;
FirebaseUser firebaseUser;
ArrayList <String> NameList;
Search_Adapter_lecturer search_adapter_lecturer;
String lecturer_name2,lectuer_email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_lecturer);
search_lecturer = findViewById(R.id.search_Lecturer);
recyclerView = findViewById(R.id.recyclerView_Lect);
databaseReference = FirebaseDatabase.getInstance().getReference();
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
NameList = new ArrayList<>();
search_lecturer.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()){
setAdapter(s.toString());
} else {
NameList.clear();
recyclerView.removeAllViews();
}
}
});
}
private void setAdapter(final String searchString) {
final Intent intent2 = null;
databaseReference.child("lecturer").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
NameList.clear();
recyclerView.removeAllViews();
int counter = 0;
for (DataSnapshot snapshot: dataSnapshot.getChildren()){
String uid = snapshot.getKey();
String Lect_Name = snapshot.child("Name").getValue(String.class);
if(Lect_Name.contains(searchString)){
NameList.add(Lect_Name);
counter++;
}
if (counter == 10){
break;
}
}
search_adapter_lecturer = new Search_Adapter_lecturer(Search_lecturer.this, NameList);
recyclerView.setAdapter(search_adapter_lecturer);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
Adapter class
public class Search_Adapter_lecturer extends RecyclerView.Adapter<Search_Adapter_lecturer.SearchViewHolder> {
Context context;
ArrayList<String> NameList;
class SearchViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView lect_name, lect_email;
public SearchViewHolder(#NonNull View itemView) {
super(itemView);
itemView.setOnClickListener(this);
lect_name = itemView.findViewById(R.id.lect_name);
lect_email = itemView.findViewById(R.id.lecturer_email);
}
#Override
public void onClick(View v) {
Intent intent = new Intent(context, notification_menu.class);
context.startActivity(intent);
}
}
public Search_Adapter_lecturer(Context context, ArrayList<String> nameList) {
this.context = context;
this.NameList = nameList;
}
#NonNull
#Override
public Search_Adapter_lecturer.SearchViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.search_list_items, viewGroup, false);
return new Search_Adapter_lecturer.SearchViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull SearchViewHolder searchViewHolder, int position) {
searchViewHolder.lect_name.setText(NameList.get(position));
}
#Override
public int getItemCount() {
return NameList.size();
}
}
I tried to implement a search function into my application. I learn from a tutorial from youtube. It works but now I can't seem to find a way for which after the search, user manage to click on the name list and redirect to another activity with the data that the user clicks on. Hope to learn from you guys.

Data appear in fire base console but didn't appear in the simulator

I create fire base Real time data base project and try to display student List in Recycler View, the data appear normally in fire base console but didn't appear in the simulator ?
Here is the Recycler View Class code :
public class StudentAdapter extends RecyclerView.Adapter<StudentAdapter.StudentHolder> {
private Context context;
private List<Student> studentList;
public StudentAdapter(Context context, List<Student> studentList) {
this.context = context;
this.studentList = studentList;
}
#Override
public StudentHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View row = LayoutInflater.from(parent.getContext()).inflate(R.layout.student_row, parent, false);
return new StudentHolder(row);
}
#Override
public void onBindViewHolder(StudentHolder holder, int position) {
final Student student = studentList.get(position);
holder.studentNameTv.setText(student.getName());
holder.studentAvgTv.setText(String.valueOf(student.getAverage()));
holder.editStudentBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, EditStudentActivity.class);
intent.putExtra("name", student.getName());
context.startActivity(intent);
}
});
holder.deleteStudentBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference();
Query query = ref.child("students").orderByChild("name").equalTo(student.getName());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
snapshot.getRef().removeValue();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
#Override
public int getItemCount() {
return studentList.size();
}
class StudentHolder extends RecyclerView.ViewHolder {
TextView studentNameTv, studentAvgTv;
Button deleteStudentBtn, editStudentBtn;
public StudentHolder(View itemView) {
super(itemView);
studentNameTv = (TextView) itemView.findViewById(R.id.student_name);
studentAvgTv = (TextView) itemView.findViewById(R.id.student_avg);
deleteStudentBtn = (Button) itemView.findViewById(R.id.delete_student);
editStudentBtn = (Button) itemView.findViewById(R.id.edit_student);
}
}
}
and Here is the Main Activity Class code :
public class MainActivity extends AppCompatActivity {
List<Student> studentList = new ArrayList<>();
StudentAdapter adapter;
DatabaseReference ref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final FirebaseDatabase database = FirebaseDatabase.getInstance();
ref = database.getReference();
ref.child("students").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
studentList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Student student = snapshot.getValue(Student.class);
studentList.add(student);
adapter.notifyDataSetChanged();
}
Collections.reverse(studentList);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rv);
adapter = new StudentAdapter(MainActivity.this, studentList);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
recyclerView.setAdapter(adapter);
SearchView searchView = (SearchView) findViewById(R.id.search_view);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
Query fireQuery = ref.child("students").orderByChild("name").equalTo(query);
fireQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() == null) {
Toast.makeText(MainActivity.this, "ERROR", Toast.LENGTH_SHORT).show();
} else {
List<Student> searchList = new ArrayList<Student>();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Student student = snapshot.getValue(Student.class);
searchList.add(student);
adapter = new StudentAdapter(MainActivity.this, searchList);
recyclerView.setAdapter(adapter);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
searchView.setOnCloseListener(new SearchView.OnCloseListener() {
#Override
public boolean onClose() {
adapter = new StudentAdapter(MainActivity.this, studentList);
recyclerView.setAdapter(adapter);
return false;
}
});
}
}

Categories

Resources