Detect have a zero length - java

public class c_Fragment_Chat extends Fragment {
private RecyclerView recyclerView;
private UserAdapter userAdapter;
private List<User> mUsers;
EditText s_search_student;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.c_fragment_chat, container, false);
recyclerView = view.findViewById(R.id.c_recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
mUsers = new ArrayList<>();
readUsers();
s_search_student = view.findViewById(R.id.s_search_student);
s_search_student.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
searchUsers(charSequence.toString().toLowerCase());
}
#Override
public void afterTextChanged(Editable editable) {
}
});
return view;
}
private void searchUsers(String s) {
Query query = FirebaseDatabase.getInstance().getReference("User").orderByChild("search")
.startAt(s)
.endAt(s+"\uf8ff");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(s_search_student.getText().toString().equals("")){
mUsers.clear();
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
User user = snapshot.getValue(User.class);
mUsers.add(user);
}
userAdapter = new UserAdapter(getContext(), mUsers, false);
recyclerView.setAdapter(userAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void readUsers() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("User");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mUsers.clear();
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
User user = snapshot.getValue(User.class);
mUsers.add(user);
}
userAdapter = new UserAdapter(getContext(), mUsers, false);
recyclerView.setAdapter(userAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero-length
I don't know why my edit text can't able to detect the data changed from the string. Please give me a hand~ thank you very much. And the above is the error problem that I get.

Related

How to Search for data in Firebase android studio

I have an algorithm looking for Firebase data but it doesn't work and records an error to me, I want to register into Edittext Value and it will bring me the appropriate card
I use the recylerView
recyclerView= findViewById(R.id.recycleview);
getmRootFLY = FirebaseDatabase.getInstance().getReference("FLY");
list = new ArrayList<>();
arrayList = new ArrayList<>();
recyclerView.setLayoutManager(new LinearLayoutManager(this));
myAdapter = new MyAdapter(this,list);
recyclerView.setAdapter(myAdapter);
getmRootFLY.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot: snapshot.getChildren())
{
Fly fly = dataSnapshot.getValue(Fly.class);
list.add(fly);
}
myAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
databaseReference = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
mRootRef = FirebaseDatabase.getInstance().getReference().child("Users").child(mAuth.getCurrentUser().getUid()).child("First Name");
mRootRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String name = dataSnapshot.getValue().toString();
TextView myLoginTextFromDB = (TextView)findViewById(R.id.hello_name_from_db);
myLoginTextFromDB.setText(name);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
EditText editTextTextPersonName = (EditText) findViewById(R.id.editTextTextPersonName);
editTextTextPersonName.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
Query query = databaseReference.child("FLY").equalTo(editable.toString());
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
{
list.clear();
for (DataSnapshot dss: snapshot.getChildren())
{
final Fly fly = dss.getValue(Fly.class);
list.add(fly);
}
MyAdapter myAdapter1 = new MyAdapter(getApplicationContext(),list);
recyclerView.setAdapter(myAdapter1);
myAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
});
}
It is important to note Getmrootfly adds the card to the array and basically shows me the data available in Firebase
And all code that appears as an edittexttexteonname is a code that needs to look for the data

Why the chat list is not appearing?

It is like social media app,This fragment should display the chat list, But it isn't, Here is the codes:
DirectMessagesFragment:
public class DirectMessagesFragment extends Fragment{
FirebaseAuth firebaseAuth;
FirebaseUser currentUser;
AdapterChatlist adapterChatlist;
DatabaseReference ref;
RecyclerView recyclerViewChatter;
List<ModelChatter> chatterList ;
List<ModelChatlist> chatlistList ;
public DirectMessagesFragment(){}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
setHasOptionsMenu(true);
View view = inflater.inflate(R.layout.fragment_direct_messages, container, false);
firebaseAuth = FirebaseAuth.getInstance();
currentUser = FirebaseAuth.getInstance().getCurrentUser();
recyclerViewChatter = view.findViewById(R.id.chatter_recyclerview);
chatlistList = new ArrayList<>();
ref = FirebaseDatabase.getInstance().getReference("Chatlist").child(currentUser.getUid());
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
chatlistList.clear();
for (DataSnapshot ds:snapshot.getChildren()){
ModelChatlist chatlist = ds.getValue(ModelChatlist.class);
chatlistList.add(chatlist);}
loadChats();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {}
});
return view;
}
private void loadChats() {
chatterList = new ArrayList<>();
ref = FirebaseDatabase.getInstance().getReference("Users");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
chatterList.clear();
for (DataSnapshot ds:snapshot.getChildren()){
ModelChatter chatter = ds.getValue(ModelChatter.class);
for(ModelChatlist chatlist: chatlistList){
if(chatter.getUid() != null && chatter.getUid().equals(chatlist.getId())){
chatterList.add(chatter);
break;
}}
adapterChatlist = new AdapterChatlist(getContext(), chatterList);
recyclerViewChatter.setAdapter(adapterChatlist);
}}
#Override
public void onCancelled(#NonNull DatabaseError error) {}
});
}}
In ChatActivity:
//create chat list in firebase
DatabaseReference ref1 =
FirebaseDatabase.getInstance().getReference("ChatList")
.child(uid).child(hisUid);
ref1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(!snapshot.exists()){
ref1.child("id").setValue(hisUid);
}}
#Override
public void onCancelled(#NonNull DatabaseError error) {}
});
DatabaseReference ref2 = FirebaseDatabase.getInstance().getReference("ChatList")
.child(hisUid).child(uid);
ref2.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(!snapshot.exists()){
ref2.child("id").setValue(uid);
}}
#Override
public void onCancelled(#NonNull DatabaseError error) {}
});}
#Override
public void afterTextChanged(Editable s) {
}
};
/////////
}
ModelChatlist only contain id.
ModelChatter contain name, image, uid.
AdapterChatlist:
public class AdapterChatlist extends RecyclerView.Adapter<AdapterChatlist.MyHolder>{
Context context;
List<ModelChatter> chattersList;
public AdapterChatlist(Context context, List<ModelChatter> chattersList) {
this.context = context;
this.chattersList = chattersList;
}
#NonNull
#Override
public MyHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.row_dm, parent, false);
return new MyHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyHolder holder, int position) {
String userImage = chattersList.get(position).getImage();
String userName = chattersList.get(position).getName();
String hisUid = chattersList.get(position).getUid();
holder.chatter_name.setText(userName);
try {
Picasso.with(context).load(userImage).placeholder(R.drawable.user).into(holder.chatter_img);
} catch (Exception e){
Picasso.with(context).load(R.drawable.user).into(holder.chatter_img);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, ChatActivity.class);
intent.putExtra("hisUid", hisUid);
context.startActivity(intent);
}
});}
#Override
public int getItemCount() {
return chattersList.size();}
class MyHolder extends RecyclerView.ViewHolder{
ImageView chatter_img;
TextView chatter_name;
public MyHolder(#NonNull View itemView) {
super(itemView);
chatter_img = itemView.findViewById(R.id.chatter_img);
chatter_name = itemView.findViewById(R.id.chatter_name);
}}}}
fragment_direct_messages layout contain the recyclerview, row_dm contain the cardview
Any help will be appreciated..
Pass chat list into your method
for (DataSnapshot ds:snapshot.getChildren()){
ModelChatlist chatlist = ds.getValue(ModelChatlist.class);
chatlistList.add(chatlist);
}
loadChats(chatlistList);
private void loadChats(List<ModelChatlist> chatlist) {
//your code
}
Try adding filters (like logging the data received) to check where the actual problem persists. It's difficult to go through so much code.

Firebase database set objects in favorite list

I have a problem clearing list in fragments. I need to clear the list when happening update in fragment. I already put it in different places but it does not help me.
When an update happens in fragment it shows the same list but that list also add elements from the previous list. If I put list.clear(); in the moment when it rakes arguments from firebase it did not give me needed effect, when I put it in onCreate() method then app gives me error.
public class Favourite extends Fragment {
private RecyclerView recyclerView;
private ArrayList<TourReader1> artistList;
private ToursAdapter1 adapter1;
private DatabaseReference reference,reference2;
String uid;
public Favourite() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
//Get current user id
uid = user.getUid();
//Connect to specific point in database Tours
reference = FirebaseDatabase.getInstance().getReference("Tours");
//Create add to method valuelistener or reference which is specific point in database
reference2 = FirebaseDatabase.getInstance().getReference("user").child(uid);
reference.addValueEventListener(valueEventListener);
reference.keepSynced(true);
}
ValueEventListener valueEventListener = (new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot1) {
//get all information from specific point of database
for (DataSnapshot datasnapshot : snapshot1.getChildren()) {
//get current name of starting point from where we recive information from database
String firstname = datasnapshot.getKey();
//valuelistener for another point from database
reference2.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dSnapshot2:snapshot.getChildren()){
String seconame = dSnapshot2.getKey();
Boolean control = dSnapshot2.child("like").getValue(Boolean.class);
if(control != null&&firstname.equals(seconame) &&control.equals(true)) {
TourReader1 artist = datasnapshot.getValue(TourReader1.class);
artistList.add(artist);
}
}
adapter1.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
artistList = new ArrayList<>();
View rootview = inflater.inflate(R.layout.favourite, container, false);
recyclerView = rootview.findViewById(R.id.list);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
adapter1 = new ToursAdapter1(getContext(), artistList);
recyclerView.setAdapter(adapter1);
GridLayoutManager mGridLayoutManager = new GridLayoutManager(getContext(), 2);
recyclerView.setLayoutManager(mGridLayoutManager);
return rootview;
}
}
You should clear the artistList using artistList.clear() before your for loop in onDataChangeas this list is having the data from the last callback triggered.
Ok, I found the answer myself, I clear my list in the adapter by tourlist.clear() and remove userpoints.keepSynced(true); when like icon is false.
holder.sparkButton.setEventListener(new SparkEventListener() {
#Override
public void onEvent(ImageView button, boolean buttonState) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String uid = user.getUid();
DatabaseReference userpoints = FirebaseDatabase.getInstance().getReference("user").child(uid);
ToursLike registerDatabase = new ToursLike(true);
if(buttonState){
userpoints.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.hasChild(tour.Name)) {
userpoints.child(tour.Name).setValue(registerDatabase);
userpoints.keepSynced(true);
tourList.clear();
}
else{
userpoints.child(tour.Name).child("like").setValue(true);
userpoints.keepSynced(true);
tourList.clear();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
else{
userpoints.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
userpoints.child(tour.Name).child("like").setValue(false);
tourList.clear();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
#Override
public void onEventAnimationEnd(ImageView button, boolean buttonState) {
}
#Override
public void onEventAnimationStart(ImageView button, boolean buttonState) {
}
});
}

Recyclerview's Onscroll is not working while fetching data from firebase

I want to add onScroll Listener, but recyclerview's addonScrollListner() method is not doing anything, I want to fetch next ten items on every recyclerview's scroll.
At first time the data is fetching fine, but when i am scrolling recyclerview then nothing is happening, i am not able to find out why is this happening.
It is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_content);
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
mAdView = findViewById(R.id.adView_con);
progressBar = findViewById(R.id.contentprogressbar);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
recyclerView = findViewById(R.id.listview);
mSwipeRefreshLayout = findViewById(R.id.swipeContainer);
textView = findViewById(R.id.emptylist);
backbtncontent = findViewById(R.id.backbtncntent);
backbtncontent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(ContentActivity.this, HomeActivity.class);
startActivity(i);
}
});
classname = getIntent().getStringExtra("classname");
if (classname.equals("A")) {
content = getIntent().getStringExtra("jokecontent");
} else if (classname.equals("B")) {
content = getIntent().getStringExtra("shayaricontent");
}
getLastKeyFromFirebase();
final LinearLayoutManager layoutManager= new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(), layoutManager.getOrientation());
recyclerView.addItemDecoration(dividerItemDecoration);
arrayAdapter = new NewAdapterContent(contentname,this);
recyclerView.setAdapter(arrayAdapter);
getUsers();
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(#NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
total_item = layoutManager.getItemCount();
last_visible_item = layoutManager.findLastCompletelyVisibleItemPosition();
if(!isLoading && total_item<=((last_visible_item+ITEM_LOAD_COUNT))){
getUsers();
isLoading = true;
}
}
});
}
private void getUsers()
{
if (!isMaxData) {
Query query;
if (classname.equals("A")) {
if (TextUtils.isEmpty(last_nodes)) //wait content to aa n raehre
query = FirebaseDatabase.getInstance().getReference("ContentJokes")
.orderByChild("subcategory")
.equalTo(content)
.limitToFirst(ITEM_LOAD_COUNT);
else
query = FirebaseDatabase.getInstance().getReference("ContentJokes")
.orderByChild("subcategory")
//.equalTo(content)
.startAt(last_nodes)
.limitToFirst(ITEM_LOAD_COUNT);
//1 sec wait cll ari kisi ki
query.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
if (!dataSnapshot.exists()) {
//hello ?
isLoading = false;
isMaxData = true;
// progressBar.setVisibility(View.GONE);
Toast.makeText(ContentActivity.this, "There is no jokes present under this category", Toast.LENGTH_SHORT).show();
} else {
String contentdisplay = dataSnapshot.child("content").getValue(String.class);
String key = dataSnapshot.child("content").getKey();
ContentModel contentModel = new ContentModel(contentdisplay, key);
contentname.add(0, contentModel);
arrayAdapter.notifyDataSetChanged();
progressBar.setVisibility(View.GONE);
arrayAdapter.notifyItemInserted(0);
last_nodes = contentname.get(contentname.size() - 1).getId();
if (!last_nodes.equals(last_key)) {
} else
last_nodes = last_key;
isLoading = false;
}
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
} else if(classname.equals("B")){
if (TextUtils.isEmpty(last_nodes)) //wait content to aa n raehre
query = FirebaseDatabase.getInstance().getReference("ContentShayari")
.orderByChild("subcategory")
.equalTo(content)
.limitToFirst(ITEM_LOAD_COUNT);
else
query = FirebaseDatabase.getInstance().getReference("ContentShayari")
.orderByChild("subcategory")
.equalTo(content)
.startAt(last_nodes)
.limitToFirst(ITEM_LOAD_COUNT);
query.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
if (!dataSnapshot.exists()) {
isLoading = false;
isMaxData = true;
// progressBar.setVisibility(View.GONE);
Toast.makeText(ContentActivity.this, "There is no jokes present under this category", Toast.LENGTH_SHORT).show();
} else {
String contentdisplay = dataSnapshot.child("content").getValue(String.class);
String key = dataSnapshot.child("content").getKey();
ContentModel contentModel = new ContentModel(contentdisplay, key);
contentname.add(0, contentModel);
arrayAdapter.notifyDataSetChanged();
// progressBar.setVisibility(View.GONE);
arrayAdapter.notifyItemInserted(0);
last_nodes = contentname.get(contentname.size() - 1).getId();
if (!last_nodes.equals(last_key)) {
} else
last_nodes = last_key;
isLoading = false;
}
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
}
private void getLastKeyFromFirebase() {
Query getLastKey;
if (classname.equals("A")) {
getLastKey = FirebaseDatabase.getInstance().getReference()
.child("ContentJokes")
.orderByChild("subcategory").equalTo(content)
.limitToLast(1);
getLastKey.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot lastKey : dataSnapshot.getChildren()) {
last_key = lastKey.getKey();
Toast.makeText(ContentActivity.this, String.valueOf(last_key), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(ContentActivity.this, "cannot get last key", Toast.LENGTH_SHORT).show();
}
});
} else if (classname.equals("B")) {
getLastKey = FirebaseDatabase.getInstance().getReference()
.child("ContentShayari")
.orderByChild("subcategory").equalTo(content)
.limitToLast(1);
getLastKey.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot lastKey : dataSnapshot.getChildren()) {
last_key = lastKey.getKey();
Toast.makeText(ContentActivity.this, String.valueOf(last_key), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(ContentActivity.this, "cannot get last key", Toast.LENGTH_SHORT).show();
}
});
}
}
RecyclerAdapter Code:
public class NewAdapterContent extends RecyclerView.Adapter<NewAdapterContent.ViewHolder> {
ArrayList<ContentModel>contentModels;
Context context;
public NewAdapterContent(ArrayList<ContentModel>contentModels, Context context) {
this.contentModels = contentModels;
this.context = context;
}
public void addAll(ArrayList<ContentModel>contentModels){
int initSize = contentModels.size();
contentModels.addAll(contentModels);
notifyItemRangeChanged(initSize, contentModels.size());
}
public String getLastItemId(){
return contentModels.get(contentModels.size()-1).getId();
}
#NonNull
#Override
public NewAdapterContent.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.content, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull NewAdapterContent.ViewHolder holder, int position) {
holder.textView.setText(contentModels.get(position).getContent());
}
#Override
public int getItemCount() {
return contentModels.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView textView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.contentText);
}
}
}
Anytime of help would be appreciated. Please help.
Try it which is very easy to use that was worked for me by using the custom RecyclerView.OnScrollListener named EndlessRecyclerViewScrollListener -
EndlessRecyclerViewScrollListener scrollListener = new
EndlessRecyclerViewScrollListener(layoutManager) {
#Override
public void onLoadMore(int page, int totalItemsCount, RecyclerView view) {
if(!isLoading){
getUsers();
isLoading = true;
}
}
};
recyclerView.addOnScrollListener(scrollListener);

I have a editText that acts as a Searchbar, How do I hide recyclerView items if user hasn't typed anything on the Searchbar

I want the items to appear only when the user starts typing something on the EditText
Here's my Adapter:
#NonNull
#Override
public UserAdapter.ImageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.user_item, parent, false);
return new UserAdapter.ImageViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final UserAdapter.ImageViewHolder holder, final int position) {
...
}
Here's the Search Fragment:
userList = new ArrayList<>();
userAdapter = new UserSearchMessageAdapter(getContext(), userList, true);
recyclerView.setAdapter(userAdapter);
readUsers();
search_bar.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
searchUsers(charSequence.toString().toLowerCase());
}
#Override
public void afterTextChanged(Editable editable) {
}
});
return view;
}
private void searchUsers(String s){
Query query = FirebaseDatabase.getInstance().getReference("Users").orderByChild("username")
.startAt(s)
.endAt(s+"\uf8ff");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
userList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
User user = snapshot.getValue(User.class);
userList.add(user);
}
userAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void readUsers() {
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (search_bar.getText().toString().equals("")) {
userList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
User user = snapshot.getValue(User.class);
userList.add(user);
}
userAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
EDIT
You can hide the recyclerview when the user hasnt typed anything in the edittext
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if(charSeqeunce.equals(""))recyclerView.setVisibility(View.GONE);
else {searchUsers(charSequence.toString().toLowerCase());
recyclerView.setVisibility(View.VISIBLE);
}
}
and you can just show an empty state image instead.
When the user types something in the edittext then you can show them the recyclerview back and hide the empty state image!
Hope this helps!

Categories