This question already has answers here:
How do I check if my EditText fields are empty? [closed]
(30 answers)
Closed 2 years ago.
I have tried other questions and answer but have not found a solution.
I am creating a social app that let's people search for others. When I click the search bar I want and type in a letter, for e.g. B, I see the list of users with the name B as expected. But when I removed the B and the search bar is empty, the list of users still shows up.
When nothing is in the search bar, I want the list of users to disappear. This is how I create the edit text in my activity_search:
<EditText
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_marginHorizontal="5dp"
android:hint="Search Username Here"
android:textSize="22dp"
android:id="#+id/input"
android:inputType="text"
android:layout_gravity="center"
android:background="#drawable/round_edit_text" />
This is where I set that edit text in the java activity:
input = findViewById(R.id.input);
And this is the whole java file:
EditText input;
RecyclerView FindFriendsRecyclerList;
DatabaseReference mRef;
Query query;
Context mContext;
TextWatcher textWacher;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
input = findViewById(R.id.input);
input.addTextChangedListener(textWacher);
TextWatcher textWacher = 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) {
String strText = s.toString();
if (strText .length() == 0) {
// removeList();
FindFriendsRecyclerList.setVisibility(View.INVISIBLE);
Toast.makeText(mContext, "Remove list", Toast.LENGTH_SHORT).show();
} else {
// showList();
}
}
#Override
public void afterTextChanged(Editable s) {
}
};
FindFriendsRecyclerList = (RecyclerView) findViewById(R.id.recycler);
FindFriendsRecyclerList.setLayoutManager(new LinearLayoutManager(this));
findViewById(R.id.search).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mRef = FirebaseDatabase.getInstance().getReference().child("Users");
query = mRef.orderByChild("fullname").orderByChild("username").startAt(input.getText().toString()).endAt(input.getText().toString()+"\uf8ff");
setdata();
}
});
checkIfEmpty();
if (input.getText().toString().length() == 0) {
FindFriendsRecyclerList.setVisibility(View.INVISIBLE);
}
}
private void setdata() {
FirebaseRecyclerOptions<User> options =
new FirebaseRecyclerOptions.Builder<User>()
.setQuery(query, User.class)
.build();
FirebaseRecyclerAdapter<User, FindFriendsViewHolder> adapter =
new FirebaseRecyclerAdapter<User, FindFriendsViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull FindFriendsViewHolder holder, final int position, #NonNull User model) {
holder.userName.setText(model.getUsername());
holder.userFullName.setText(model.getFullname());
Picasso.get().load(model.getImageurl()).placeholder(R.drawable.profile_pic).into(holder.profileImage);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//String visit_user_id = getRef(position).getKey();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.search_users, new ProfileFragment()).commit();
}
});
}
#NonNull
#Override
public FindFriendsViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.user_item, viewGroup, false);
FindFriendsViewHolder viewHolder = new FindFriendsViewHolder(view);
return viewHolder;
}
};
FindFriendsRecyclerList.setAdapter(adapter);
adapter.startListening();
}
public static class FindFriendsViewHolder extends RecyclerView.ViewHolder {
public TextView userName, userFullName;
public CircleImageView profileImage;
public FindFriendsViewHolder(#NonNull View itemView) {
super(itemView);
userName = itemView.findViewById(R.id.username);
userFullName = itemView.findViewById(R.id.fullname);
profileImage = itemView.findViewById(R.id.image_profile);
}
}
public void checkIfEmpty() {
TextWatcher textWacher = 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) {
String strText = s.toString();
if (strText.length() == 0) {
FindFriendsRecyclerList.setVisibility(View.INVISIBLE);
} else {
// showList();
}
}
#Override
public void afterTextChanged(Editable s) {
FindFriendsRecyclerList.setVisibility(View.INVISIBLE);
}
};
}
As you can see above I have tried the following two ways to check if it's empty:
if (input.getText().toString().length() == 0) {
FindFriendsRecyclerList.setVisibility(View.INVISIBLE);
}
public void checkIfEmpty(View v){
if(input.getText().toString().equals("")) {
input.setVisibility(View.INVISIBLE);
}
}
You only call checkIfEmpty on method onCreate if you want yo check on every change if an EditText is empty you need to add to your "input" EditText an onDataChangeListener and check on every mover if is empty.
use TextWatcher for get text state in EditText.
for example,
public class MainActivity extends AppCompatActivity {
private EditText input;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
input = (EditText) findViewById(R.id.input);
input.addTextChangedListener(textWacher);
}
TextWatcher textWacher = 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) {
String strText = s.toString();
if (strText .length() == 0) {
// removeList();
Toast.makeText(MainActivity.this, "remove", Toast.LENGTH_SHORT).show();
} else {
// showList();
Toast.makeText(MainActivity.this, "show", Toast.LENGTH_SHORT).show();
}
}
#Override
public void afterTextChanged(Editable s) {
}
};
}
Related
So I have a RecyclerView consisting of EditTexts that uses an ArrayList as its data set, when the EditTexts are edited I want that ArrayList to be updated as well and I want to be able to use it in the Main Activity currently I've tried implementing a TextChangedListener however I have no clue how to get the data and transfer it to my list. Here's the code:
Main Activity:
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
public ArrayList playerList;
private Button runItButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
playerList = new ArrayList();
for(int i = 0; i < 4; i++){
playerList.add("Player " + (i + 1));
}
runItButton = findViewById(R.id.buttonStartGame);
runItButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, DrinktasksActivity.class);
intent.putExtra("playerList", playerList);
startActivity(intent);
}
});
recyclerView = findViewById(R.id.recyclyerViewNames);
MyAdapter myAdapter = new MyAdapter(this, playerList);
recyclerView.setAdapter(myAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
public void addPlayers(View view){
playerList.add("Player " + (playerList.size() + 1));
recyclerView.getAdapter().notifyDataSetChanged();
}
}
The adapter:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
Context context;
ArrayList playerList;
public MyAdapter(Context ct, List players){
context = ct;
playerList = (ArrayList) players;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.enter_name, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
String current = playerList.get(position).toString();
holder.editText.setHint(current);
holder.editText.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) {
// The code I assume should go here but I don't know how to implement
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
#Override
public int getItemCount() {
return playerList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
EditText editText;
public ViewHolder(#NonNull View itemView) {
super(itemView);
editText = itemView.findViewById(R.id.editname);
}
}
}
All you have to do is to implement a custom callback to your activity with the index in which the edittext is edited and what is the new text.
Create a callback interface inside adapter
public interface TextChangeCallback {
void textChangedAt(int position, String text);
}
Pass the inteface implementation to Adapter via constructor
public MyAdapter(Context ct, List players,TextChangeCallback callback){
context = ct;
playerList = (ArrayList) players;
this.callback = callback;
}
Trigger callback to activity whenever you edit the text using TextWatcher
holder.editText.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) {
if (s.equals("")){
return;
}
data.set(position, String.valueOf(s));
callback.textChangedAt(position, String.valueOf(s));
}
#Override
public void afterTextChanged(Editable s) {
}
});
Add this interface implementation to your adapter
MyAdapter myAdapter = new MyAdapter(this, playerList, new MyAdapter.TextChangeCallback() {
#Override
public void textChangedAt(int position, String text) {
playerList.set(position, text);
Log.d("UPDATED LIST : ", String.valueOf(data));
}
});
recyclerView.setAdapter(myAdapter);
This will now update the ArrayList in adapter and activity as you edit the edittext from recyclerview.
You can find the complete implementation from this link
Image
I have a RecyclerView in which fields are created dynamically. To save the stored data, I used TextWatcher. But I do not know how I sum up the values that are in EditText -Cost and display the value in the TextView at the bottom of the screen
public class ItemsAdapter extends
ListAdapter<Item,ItemsAdapter.ViewHolder> {
private List<Item> mItems=new ArrayList<>();
public static final DiffUtil.ItemCallback<Item>DIFF_CALLBACK=
new DiffUtil.ItemCallback<Item>() {
#Override
public boolean areItemsTheSame( Item oldItem, Item newItem) {
return oldItem.getId()==newItem.getId();
}
#Override
public boolean areContentsTheSame(Item oldItem, Item newItem) {
return(oldItem.getName()==newItem.getName()&&oldItem.getCost()==newItem.getCost());
}
};
public ItemsAdapter(){super(DIFF_CALLBACK);}
public void addMorreItems(List<Item> newItems){
int insertionPosition=mItems.size();
mItems.addAll(newItems);
notifyItemRangeInserted(insertionPosition,newItems.size());
submitList(mItems);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
Context context=parent.getContext();
LayoutInflater inflater=LayoutInflater.from(context);
View itemView=inflater.inflate(R.layout.custom_edittext_layout,parent,false);
ViewHolder viewHolder=new ViewHolder(itemView);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder viewHolder,int position){
viewHolder.editTextName.setText(mItems.get(position).getName());
viewHolder.editTextCost3.setText(mItems.get(position).getCost());
Item item=getItem(position);
EditText editText=viewHolder.editTextName;
editText.setText(item.getName());
EditText editText1=viewHolder.editTextCost3;
editText1.setText(item.getCost());
}
public class ViewHolder extends RecyclerView.ViewHolder {
public EditText editTextName;
public EditText editTextCost3;
public TextView txtTipAmount3;
public Button buttonDelete;
public Button buttonOK;
public ViewHolder(View itemView){
super(itemView);
editTextCost3=(EditText)itemView.findViewById(R.id.ediCost3);
editTextName=(EditText)itemView.findViewById(R.id.editTextEnterYourName);
txtTipAmount3=(TextView)itemView.findViewById(R.id.txtTipAmount3);
buttonDelete=(Button)itemView.findViewById(R.id.buttonDelete);
buttonOK=(Button)itemView.findViewById(R.id.buttonOk);
buttonDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position=getAdapterPosition();
try {
mItems.remove(position);
notifyItemRemoved(position);
}catch (ArrayIndexOutOfBoundsException e){e.printStackTrace();}
}
});
editTextName.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) {
mItems.get(getAdapterPosition()).setmName(editTextName.getText().toString());
}
#Override
public void afterTextChanged(Editable s) {
}
});
editTextCost3.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) {
mItems.get(getAdapterPosition()).setmCost(editTextCost3.getText().toString());
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
} }
Add callback for the Activity/Fragment that holds TextView for sum cost:
interface OnCostChangeListener {
void onChange(List<Item> list);
}
Implement it:
class MyActivity extends AppCompatActivity implements OnCostChangeListener {
//...
#Override
public void onChange(List<Item> list) {
int sum = 0;
for (Item it : list) {
sum += it.getCost();
}
((TextView) findViewById(R.id.totalCost)).setText(String.valueOf(sum));
}
//...
}
Subscribe the adapter:
private OnCostChangeListener mListener;
public ItemsAdapter(OnCostChangeListener listener){
super(DIFF_CALLBACK);
this.mListener = listener;
}
and use the listener in TextWatcher:
editTextCost3.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) {
mItems.get(getAdapterPosition()).setmCost(editTextCost3.getText().toString());
if (mListener != null) {
mListener.onChange(mItems);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
UPD. It's supposed cost is stored in Item as number (integer, in the sample), not string
I have RecyclerView(CardStackView) With 60 items.
Now After finish All Items .. I have Blank Page .. I do not want to Show The blank Page if all items finished ... I want to Intent to Another Activity You can see The blank Page Here
when I implement CardStackListener I Added Those Method too Like This .I want to When All card Answered Intent To ResultActivity...Like This After 60th question I want InstedOf Blank Page Intent To ResultActivity
//Card Method
#Override
public void onCardDragging(Direction direction, float ratio) {
Log.d("CardStackView", "onCardDragging: d = " + direction.name() + ", r = " + ratio);
}
#Override
public void onCardSwiped(Direction direction) {
Log.d("CardStackView", "onCardSwiped: p = " + manager.getTopPosition() + ", d = " + direction);
if (manager.getTopPosition() == mbtiQuestAdapter.getItemCount() - 5) {
mbtiQuestAdapter.addQuestion(questions);
mbtiQuestAdapter.notifyDataSetChanged();
}
position++;
Intent intent = new Intent(MbtiQuestionActivity.this, ResultActivity.class);
intent.putExtra(RESULT, result);
Log.i(TAG, "onResultClick: " + result);
startActivity(intent);
}
#Override
public void onCardRewound() {
Log.d("CardStackView", "onCardRewound: " + manager.getTopPosition());
}
#Override
public void onCardCanceled() {
Log.d("CardStackView", "onCardCanceled:" + manager.getTopPosition());
}
Adapter.java
public class MbtiQuestAdapter extends RecyclerView.Adapter<MbtiQuestAdapter.MbtiQuestViewHolder> {
private List<Question> questionList;
private LayoutInflater layoutInflater;
private final OnItemClickListener listener;
private static final String TAG = "MbtiQuestAdapter";
public interface OnItemClickListener {
void onItemClick(int position, char value);
}
public MbtiQuestAdapter(List<Question> questionList, OnItemClickListener listener) {
this.questionList = questionList;
this.listener = listener;
}
#NonNull
#Override
public MbtiQuestViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (layoutInflater == null) {
layoutInflater = LayoutInflater.from(parent.getContext());
}
MbtiItemRowBinding binding = DataBindingUtil.inflate(layoutInflater,
R.layout.mbti_item_row, parent, false);
return new MbtiQuestViewHolder(binding);
}
#Override
public void onBindViewHolder(#NonNull final MbtiQuestViewHolder holder, final int position) {
final Question question = questionList.get(position);
holder.binding.txtQuesNum.setText(String.valueOf(position + 1));
holder.binding.txtQuesTitle.setText(question.getQuestion());
holder.binding.firstQues.setText(question.getAnswers().get(0).getAnswer());
holder.binding.secondQues.setText(question.getAnswers().get(1).getAnswer());
holder.binding.firstQues.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onItemClick(position, question.getAnswers().get(0).getValue());
}
});
holder.binding.secondQues.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onItemClick(position, question.getAnswers().get(1).getValue());
}
});
holder.binding.setQuestion(question);
}
#Override
public int getItemCount() {
Log.i(TAG, " List Size : " + questionList.size());
return questionList.size();
}
class MbtiQuestViewHolder extends RecyclerView.ViewHolder {
private MbtiItemRowBinding binding;
MbtiQuestViewHolder(MbtiItemRowBinding binding) {
super(binding.getRoot());
this.binding = binding;
}
}
public void addQuestion(List<Question> questions) {
this.questionList.addAll(questions);
}
}
SetUp CardStackView In Activity
//Swipe RecyclerView with CardStackView
cardStackView = binding.cardStackView;
manager = new CardStackLayoutManager(this);
mbtiQuestAdapter = new MbtiQuestAdapter(questions, this);
cardStackView.setLayoutManager(manager);
cardStackView.setAdapter(mbtiQuestAdapter);
I want to Say If The items Finished Do SomeThing (Show Dialog or etc.)
Thank Guys
Working Code
private CardStackView cardStackView;
private CardStackLayoutManager layoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//
layoutManager = new CardStackLayoutManager(getApplicationContext(), this);
cardStackView.setLayoutManager(layoutManager);
//
}
#Override
public void onCardSwiped(Direction direction) {
if (layoutManager.getTopPosition() == adapter.getItemCount()) {
// -------------------- last position reached, do something ---------------------
startActivity(new Intent(this, MainActivity.class));
}
}
You have CardStackLayoutManager. When card is swiped, callback comes in onCardSwiped.
Here you will get top position (position displayed on top), and total item count.
If top_position == total_item_count, then it is last position, now you can do anything.
Below is Output or same
Use position to check if you have arrived to last item. Inside onBindViewHolder method
if( position+ 1 == questionList.size()){
// you are at the last item
}
You ca try this by using scrollChangeListener like :
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
LinearLayoutManager layoutManager=LinearLayoutManager.class.cast(recyclerView.getLayoutManager());
int totalItemCount = layoutManager.getItemCount();
int lastVisible = layoutManager.findLastVisibleItemPosition();
boolean endHasBeenReached = lastVisible + 5 >= totalItemCount;
if (totalItemCount > 0 && endHasBeenReached) {
//you have reached to the bottom of your recycler view
}
}
});
Some code correction, it is better not to create listeners in onBindViewHolder() because it will be set each time this method called, better to set ones in ViewHolder
For example :
Override
public void onBindViewHolder(#NonNull final MbtiQuestViewHolder holder, final int position) {
holder.bind(questionList.get(position))
}
class MbtiQuestViewHolder extends RecyclerView.ViewHolder {
private MbtiItemRowBinding binding;
MbtiQuestViewHolder(MbtiItemRowBinding binding) {
super(binding.getRoot());
this.binding = binding;
binding.firstQues.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onItemClick(getAdapterPosition(), questionList.get(getAdapterPosition()).getAnswers().get(0).getValue());
}
});
binding.secondQues.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onItemClick(getAdapterPosition(), questionList.get(getAdapterPosition()).getAnswers().get(1).getValue());
}
});
}
public void bind(Question question){
binding.txtQuesNum.setText(String.valueOf(position + 1));
binding.txtQuesTitle.setText(question.getQuestion());
binding.firstQues.setText(question.getAnswers().get(0).getAnswer());
binding.secondQues.setText(question.getAnswers().get(1).getAnswer());
binding.setQuestion(question);
}
public void addQuestion(List<Question> questions) {
this.questionList.addAll(questions);
}
}
you could compare with CardStackLayoutManager.getTopPosition(), which should be the index position currently displayed. the CardStackView GitHub explains the methods which are available.
alternatively, just count the number of swipes:
int currentPosition = 0;
#Override
public void onCardSwiped(Direction direction) {
currentPosition++;
}
//define the layoutmanager
private CardStackLayoutManager manager;
//make CardStackListener in layout manger and u need to implement methods
manager = new CardStackLayoutManager(this, new CardStackListener() {
#Override
public void onCardDragging(Direction direction, float ratio) {
}
#Override
public void onCardSwiped(Direction direction) {
}
#Override
public void onCardRewound() {
}
#Override
public void onCardCanceled() {
}
#Override
public void onCardAppeared(View view, int position) {
//here if u print position you will find the position of your viewed item and this function will call when card viewed
}
#Override
public void onCardDisappeared(View view, int position) {
Log.d("onCardDisappeared: ", "" + position);
//here if u print position you will find the position of your Disappeared item and this function will call when card disappear
}
}
});
cardStackView.setLayoutManager(manager);
cardStackView.setAdapter(cardStackAdapter);
Hello can I ask why my search view isn't filtering the list of data when searching on the fragments recyclerview and Also when I click the fragments activity again after trying to search it would result into an error
java.lang.NullPointerException: Attempt to invoke interface method
'void java.util.List.add(int, java.lang.Object)' on a null object
reference at
com.google.firebase.ikuzou.database.MemberDetailAdapter$UserChildEventListener.onChildAdded(MemberDetailAdapter.java:73)
RecyclerView Adapter
public class MemberDetailAdapter extends RecyclerView.Adapter<MemberDetailAdapter.ViewHolder> implements Filterable {
private List<User1> mUser,nUser;
private Callback mCallback;
private DatabaseReference userref;
public MemberDetailAdapter(Callback callback) {
mCallback = callback;
mUser = new ArrayList<>();
userref = FirebaseDatabase.getInstance().getReference().child("Accounts").child("Users");
userref.addChildEventListener(new UserChildEventListener());
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()){
mUser=nUser;
}else {
List<User1> filteredList = new ArrayList<>();
for (User1 row : nUser){
if (row.getFirst().toLowerCase().contains(charString.toLowerCase()) || row.getSecond().contains(charSequence)){
filteredList.add(row);
}
}
mUser=filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = mUser;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
}
};
}
class UserChildEventListener implements ChildEventListener{
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
User1 user = dataSnapshot.getValue(User1.class);
user.setKey(dataSnapshot.getKey());
mUser.add(0,user);
notifyDataSetChanged();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
String key = dataSnapshot.getKey();
User1 updatedUser = dataSnapshot.getValue(User1.class);
for (User1 user : mUser){
if (user.getKey().equals(key)){
user.setValues(updatedUser);
notifyDataSetChanged();
return;
}
}
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
String key = dataSnapshot.getKey();
for(User1 user: mUser){
if (user.getKey().equals(key)){
mUser.remove(user);
break;
}
}
notifyDataSetChanged();
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.model, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
final User1 user = mUser.get(position);
holder.mfirstNameTextView.setText(user.getFirst());
holder.msecondNameTextView.setText(user.getSecond());
holder.mnumberTextView.setText(user.getNumber());
holder.mgenderTextView.setText(user.getGender());
holder.mEmailTextView.setText(user.getEmail());
holder.mDateTextView.setText(user.getDate());
holder.mTypeTextView.setText(user.getType());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCallback.onEdit(user);
}
});
}
public void remove(User1 user) {
//TODO: Remove the next line(s) and use Firebase instead
userref.child(user.getKey()).removeValue();
}
#Override
public int getItemCount() {
if(mUser==null){
Log.v("LOG","Warn, null filteredData");
return 0;
}else{
return mUser.size();
}
}
public void add(User1 user) {
//TODO: Remove the next line(s) and use Firebase instead
userref.push().setValue(user);
}
public void update(User1 user, String newFirst,String newSecond, String newNumber, String newGender,String newDate) {
//TODO: Remove the next line(s) and use Firebase instead
user.setFirst(newFirst);
user.setSecond(newSecond);
user.setNumber(newNumber);
user.setGender(newGender);
user.setDate(newDate);
userref.child(user.getKey()).setValue(user);
}
public interface Callback {
public void onEdit(User1 user);
}
class ViewHolder extends RecyclerView.ViewHolder {
private TextView mfirstNameTextView;
private TextView msecondNameTextView;
private TextView mnumberTextView;
private TextView mgenderTextView;
private TextView mEmailTextView;
private TextView mDateTextView;
private TextView mTypeTextView;
public ViewHolder(View itemView) {
super(itemView);
mfirstNameTextView = (TextView) itemView.findViewById(R.id.firstnameTxt);
msecondNameTextView = (TextView) itemView.findViewById(R.id.lastnameTxt);
mnumberTextView = (TextView) itemView.findViewById(R.id.numberTxt);
mgenderTextView = (TextView) itemView.findViewById(R.id.genderTxt);
mEmailTextView = (TextView) itemView.findViewById(R.id.emailTxt);
mDateTextView = (TextView) itemView.findViewById(R.id.dateTxt);
mTypeTextView = (TextView) itemView.findViewById(R.id.typeTxt);
}
}
My Fragment code
public class memberFragment extends Fragment implements MemberDetailAdapter.Callback, SearchView.OnQueryTextListener {
private ListView mylistView;
private DatabaseReference db;
private Firebasehelper helper;
private CustomAdapter adapter;
private ListView lv;
private com.google.firebase.ikuzou.database.MemberDetailAdapter mAdapter;
public memberFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_member2, container, false);
mAdapter = new com.google.firebase.ikuzou.database.MemberDetailAdapter(this);
setHasOptionsMenu(true);
RecyclerView view1 = (RecyclerView) view.findViewById(R.id.recycler_view);
view1.setLayoutManager(new LinearLayoutManager(getContext()));
view1.setHasFixedSize(true);
view1.setAdapter(mAdapter);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.search_menu, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setOnQueryTextListener(this);
super.onCreateOptionsMenu(menu, inflater);
super.onCreateOptionsMenu(menu, inflater);
}
private void showAddEditDialog(final User1 user) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle(getString(user == null ? R.string.dialog_add_title : R.string.dialog_edit_title));
View view = getLayoutInflater().inflate(R.layout.input_dialog, null, false);
builder.setView(view);
final EditText firstnameEditText = (EditText) view.findViewById(R.id.firstnameEditText);
final EditText secondnameEditText = (EditText) view.findViewById(R.id.secondnameEditText);
final EditText numberEditText = (EditText) view.findViewById(R.id.numberEditText);
final EditText genderEditText = (EditText) view.findViewById(R.id.genderEditText);
final EditText emailEditText = (EditText) view.findViewById(R.id.emailEditText);
final EditText dateEditText = (EditText) view.findViewById(R.id.dateEditText);
final TextView typeEditText = (TextView) view.findViewById(R.id.typeEditText);
if (user != null) {
// pre-populate
firstnameEditText.setText(user.getFirst());
secondnameEditText.setText(user.getSecond());
numberEditText.setText(user.getNumber());
genderEditText.setText(user.getGender());
emailEditText.setText(user.getEmail());
dateEditText.setText(user.getDate());
typeEditText.setText(user.getType());
TextWatcher textWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// empty
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// empty
}
#Override
public void afterTextChanged(Editable s) {
String firstname = firstnameEditText.getText().toString();
String secondname = secondnameEditText.getText().toString();
String number = numberEditText.getText().toString();
String gender = genderEditText.getText().toString();
String date = dateEditText.getText().toString();
mAdapter.update(user, firstname,secondname,number,gender,date );
}
};
firstnameEditText.addTextChangedListener(textWatcher);
secondnameEditText.addTextChangedListener(textWatcher);
numberEditText.addTextChangedListener(textWatcher);
genderEditText.addTextChangedListener(textWatcher);
emailEditText.addTextChangedListener(textWatcher);
dateEditText.addTextChangedListener(textWatcher);
}
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (user == null) {
String firstname = firstnameEditText.getText().toString();
String secondname = secondnameEditText.getText().toString();
String number = numberEditText.getText().toString();
String gender = genderEditText.getText().toString();
String email = emailEditText.getText().toString();
String date = dateEditText.getText().toString();
mAdapter.add(new User1(firstname,secondname,number,gender, date, email));
}
}
});
builder.setNegativeButton(android.R.string.cancel, null);
builder.create().show();
// Inflate the layout for this fragment
}
#Override
public void onEdit(final User1 user) {
showAddEditDialog(user);
}
#Override
public boolean onQueryTextSubmit(String query) {
mAdapter.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String query) {
mAdapter.getFilter().filter(query);
return false;
}
Before all of this happen I have a
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()'
But changing my getItemcount into
public int getItemCount() {
if(mUser==null){
Log.v("LOG","Warn, null filteredData");
return 0;
}else{
return mUser.size();
}
}
From
public int getItemCount() {
return mUser.size();
}
Fixed the problem.
I want filter for search ListView but Does not exist class `getfilter()
I've studied in sites that these methods should be sought. I have read but I am not getting getfilter()
Who can help me get? (I'm sorry , I don't speak English good , just can read that)
public class List_bimar extends ListActivity {
TextView bimar_id;
EditText editsearch;
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sabte_bimar);
editsearch = (EditText) findViewById(R.id.btn_search);
BimarRipo repo = new BimarRipo(this);
ArrayList<HashMap<String, String>> bimartList = repo.getbimarList();
if(bimartList.size()!=0) {
ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
bimar_id = (TextView) view.findViewById(R.id.bimar_idd);
String bimarId = bimar_id.getText().toString();
Intent objIndent = new Intent(getApplicationContext(),Bimar_Detail.class);
objIndent.putExtra("bimar_id", Integer.parseInt( bimarId));
startActivity(objIndent);
}
});
final ListAdapter adapter = new SimpleAdapter( List_bimar.this,bimartList, R.layout.view_bimar_entry, new String[] { "id","namebimar" ,"shomaremeli" }, new int[] {bimar_idd, R.id.bimar_name});
setListAdapter(adapter);
editsearch.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) {
List_bimar.this.getListAdapter().
}
#Override
public void afterTextChanged(Editable editable) {
String text = editsearch.getText().toString().toLowerCase(Locale.getDefault());
}
});
}