'Android studio: SearchView doesn't update the new details of item
I'm using RecyclerView and also implemented SearchView with it. While i'm searching for an object, I can find it, I can update it details but after i success to update the data, I still see the old details of the item. only when i close the search i will see the up-to-date object. This is the class with the search functions:
public class ProductCompare extends AppCompatActivity {
Context mContext=this;
private RecyclerView mRecyclerView;
private ImageAdapterProduct mAdapter;
private DatabaseReference mDatabaseRef;
private ValueEventListener mDBListener;
private List<Product> mItem;
FloatingActionButton fab;
private int mDate, mMonth, mYear;
Date date2;
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd",java.util.Locale.getDefault());
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_compare);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
fab=findViewById(R.id.fab);
mRecyclerView=findViewById(R.id.mRecyclerView);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mItem=new ArrayList<>();
mAdapter=new ImageAdapterProduct(ProductCompare.this,mItem);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
if(dy > 0){
fab.hide();
} else{
fab.show();
}
super.onScrolled(recyclerView, dx, dy);
}
});
mDatabaseRef= FirebaseDatabase.getInstance().getReference("Product");
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final DialogPlus dialogPlus=DialogPlus.newDialog(mContext)
.setContentHolder(new ViewHolder(R.layout.dialogcontentforfab))
.setExpanded(true,1150) // was 1200
.create();
View myview=dialogPlus.getHolderView();
EditText price=myview.findViewById(R.id.price);
EditText place=myview.findViewById(R.id.place);
EditText name=myview.findViewById(R.id.name);
EditText date=myview.findViewById(R.id.date);
EditText description=myview.findViewById(R.id.description);
Button add=myview.findViewById(R.id.usubmit);
date.setOnClickListener((View v) -> {
final Calendar Cal=Calendar.getInstance();
mDate=Cal.get(Calendar.DAY_OF_MONTH);
mMonth=Cal.get(Calendar.MONTH);
mYear=Cal.get(Calendar.YEAR);
DatePickerDialog datePickerDialog=new DatePickerDialog(mContext,
(datePicker, year, month, dayOfMonth) -> {
Cal.set(year, month, dayOfMonth);
date.setText(simpleDateFormat.format(Cal.getTime()));
date2=Cal.getTime();
},mYear,mMonth,mDate);
datePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis()-1000);
datePickerDialog.show();
});
dialogPlus.show();
DAOProduct daoProduct=new DAOProduct();
add.setOnClickListener(v -> {
double pricee;
if (price.getText().toString().length() == 0) {
pricee = 0;
} else {
pricee = Double.parseDouble(price.getText().toString());
}
Product product = new Product(name.getText().toString(), pricee,
description.getText().toString(), date.getText().toString(), "נקנה מ: "+place.getText().toString());
daoProduct.add(product).addOnSuccessListener((Void suc) ->
{
dialogPlus.dismiss();
try {
InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
} catch (Exception e) {
// TODO: handle exception
}
}).addOnFailureListener(er -> {
dialogPlus.dismiss();
Toast.makeText(ProductCompare.this, "" + er.getMessage(), Toast.LENGTH_SHORT).show();
});
Toast.makeText(ProductCompare.this, "מוצר הוכנס", Toast.LENGTH_SHORT).show();
});
}
});
mDBListener = mDatabaseRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
mItem.clear();
for(DataSnapshot postSnapshot: snapshot.getChildren()){
Product product = postSnapshot.getValue(Product.class);
product.setmKey(postSnapshot.getKey());
mItem.add(product);
}
Collections.reverse(mItem);
mAdapter.notifyDataSetChanged();
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Toast.makeText(ProductCompare.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.searchmenu,menu);
MenuItem item=menu.findItem(R.id.search);
MenuItem item2=menu.findItem(R.id.sp).setVisible(false);
SearchView searchView=(SearchView)item.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String s) {
search(s);
return false;
}
@Override
public boolean onQueryTextChange(String s) {
search(s);
return false;
}
});
searchView.setOnCloseListener(new SearchView.OnCloseListener() {
@Override
public boolean onClose() {
mAdapter=new ImageAdapterProduct(mContext,mItem);
mRecyclerView.setAdapter(mAdapter);
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
private void search(String s){
Query query=mDatabaseRef.orderByChild("name").startAt(s).endAt(s+"\uf8ff");
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if(snapshot.exists()) {
List<Product> searchList = new ArrayList<>();
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
Product product = postSnapshot.getValue(Product.class);
product.setmKey(postSnapshot.getKey());
searchList.add(product);
}
ImageAdapterProduct mAdapter=new ImageAdapterProduct(ProductCompare.this,searchList);
mRecyclerView.setAdapter(mAdapter);
}
else{
List<Product> searchList = new ArrayList<>();
mAdapter=new ImageAdapterProduct(mContext,searchList);
mRecyclerView.setAdapter(mAdapter);
Toast.makeText(ProductCompare.this, "לא נמצאו תוצאות", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Toast.makeText(ProductCompare.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
mDatabaseRef.removeEventListener(mDBListener);
}}
and this is my adapter class:
public class ImageAdapterProduct extends RecyclerView.Adapter<ImageAdapterProduct.ImageViewHolder>{
private final Context mContext;
private final List<Product> mProducts;
public ImageAdapterProduct(Context context, List<Product> lProduct){
mContext=context;
mProducts=lProduct;
}
@NonNull
@Override
public ImageViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v= LayoutInflater.from(mContext).inflate(R.layout.row_product_item,parent,false);
return new ImageViewHolder(v);
}
@Override
public void onBindViewHolder(@NonNull ImageAdapterProduct.ImageViewHolder holder, int position) {
Product current = mProducts.get(position);
holder.ViewDate.setText(current.getDateOfCreate());
holder.ViewPlace.setText(current.getSupplier());
holder.ViewName.setText(current.getName());
holder.ViewDescription.setText(current.getDescription());
String price="₪"+String.valueOf(current.getPrice());
holder.ViewPrice.setText(price);
}
@Override
public int getItemCount() {
return mProducts.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder{
private int mDate, mMonth, mYear;
Date date2;
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd",java.util.Locale.getDefault());
public TextView ViewDate;
public TextView ViewName;
public TextView ViewPrice;
public TextView ViewDescription;
public TextView ViewPlace;
public ImageView imageViewDelete;
public ImageView imageViewEdit;
private DatabaseReference mDatabaseRef;
public ImageViewHolder(@NonNull View itemView) {
super(itemView);
ViewDate = itemView.findViewById(R.id.DateTextView);
ViewPrice = itemView.findViewById(R.id.PriceTextView);
ViewName=itemView.findViewById(R.id.ProductTextView);
ViewDescription=itemView.findViewById(R.id.DescriptionTextView);
ViewPlace=itemView.findViewById(R.id.PlaceTextView);
imageViewEdit=itemView.findViewById(R.id.editicon);
imageViewDelete=itemView.findViewById(R.id.deleteicon);
mDatabaseRef= FirebaseDatabase.getInstance().getReference("Product");
imageViewEdit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Product selecteditem=mProducts.get(getAdapterPosition());
final DialogPlus dialogPlus=DialogPlus.newDialog(mContext)
.setContentHolder(new ViewHolder(R.layout.dialogcontentforproduct))
.setExpanded(true,1150)
.create();
View myview=dialogPlus.getHolderView();
EditText priceOfBuy=myview.findViewById(R.id.price);
EditText supp=myview.findViewById(R.id.place);
EditText name=myview.findViewById(R.id.name);
EditText date=myview.findViewById(R.id.date);
EditText description=myview.findViewById(R.id.description);
Button update=myview.findViewById(R.id.usubmit);
priceOfBuy.setText(String.valueOf(selecteditem.getPrice()));
supp.setText(selecteditem.getSupplier());
name.setText(selecteditem.getName());
date.setText(selecteditem.getDateOfCreate());
description.setText(selecteditem.getDescription());
date.setOnClickListener((View v) -> {
final Calendar Cal=Calendar.getInstance();
mDate=Cal.get(Calendar.DAY_OF_MONTH);
mMonth=Cal.get(Calendar.MONTH);
mYear=Cal.get(Calendar.YEAR);
DatePickerDialog datePickerDialog=new DatePickerDialog(mContext, (datePicker, year, month, dayOfMonth) -> {
Cal.set(year, month, dayOfMonth);
date.setText(simpleDateFormat.format(Cal.getTime()));
date2=Cal.getTime();
},mYear,mMonth,mDate);
datePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis()-1000);
datePickerDialog.show();
});
dialogPlus.show();
update.setOnClickListener(v -> {
double priceTemp;
if (priceOfBuy.getText().toString().length() == 0) {
priceTemp = 0;
} else {
priceTemp = Double.parseDouble(priceOfBuy.getText().toString());
}
Map<String,Object> map=new HashMap<>();
//map.put("price",Double.parseDouble(price.getText().toString()));
map.put("price",priceTemp);
map.put("supplier",supp.getText().toString());
map.put("name",name.getText().toString());
map.put("dateOfCreate",date.getText().toString());
map.put("description",description.getText().toString());
FirebaseDatabase.getInstance().getReference().child("Product")
.child(selecteditem.getmKey()).updateChildren(map)
.addOnSuccessListener(unused -> {
dialogPlus.dismiss();
try {
InputMethodManager imm = (InputMethodManager)mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
} catch (Exception e) {
// TODO: handle exception
}
})
.addOnFailureListener(e -> dialogPlus.dismiss());
Toast.makeText(mContext, "נתוני פריט עודכנו", Toast.LENGTH_SHORT).show();
//notifyItemChanged(mProducts.indexOf(getAdapterPosition()),getAdapterPosition());
});
}
});
imageViewDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog.Builder builder=new AlertDialog.Builder(mContext);
builder.setTitle("מחיקת פריט");
builder.setMessage("האם ברצונך למחוק את הפריט?");
builder.setPositiveButton("כן", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Product selectedItem=mProducts.get(getAdapterPosition());
String selectedKey= selectedItem.getmKey();
mDatabaseRef.child(selectedKey).removeValue();
Toast.makeText(mContext, "פריט נמחק", Toast.LENGTH_SHORT).show();
// those 2 lines let the item disappear in search mode
mProducts.remove(getAdapterPosition());
notifyDataSetChanged();
}
});
builder.setNegativeButton("לא", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.show();
}
});
}
}}
What should i need to change / add to let it be up-to-date also in search mode? Thank you.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
