Unchecked assignment warning after creating adapter for RecyclerView - java

After creating an adapter for my RecyclerView, I noticed a warning. How can this warning be resolved?
(List) results.values in myList.addAll((List) results.values); returns a warning:
Unchecked assignment: 'java.util.List' to 'java.util.Collection <? extends com.companyname.appname.Product>'
'Product' class
public class Product {
public Product(){}
private String mProductName;
private String mProductDescription;
public Product(String productName, String productDescription) {
this.mProductName = productName;
this.mProductDescription = productDescription;
}
public String getProductName() {
return mProductName;
}
public void setProductName(String item){
this.mProductName = item;
}
public String getProductDescription() {
return mProductDescription;
}
public void setProductDescription(String description){
this.mProductDescription = description;
}
}
Activity class
public class MyActivity extends AppCompatActivity {
private static final String TAG = MyActivity.class.getSimpleName();
private Boolean mCurrentValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.md);
}
#Override
protected void onStart() {
super.onStart();
setContentView(R.layout.md);
}
}
Fragment class
public class MyFragment extends Fragment {
public MyFragment() {}
private MyListAdapter mAdapter;
RecyclerView mRecyclerView;
public boolean mTwoPane;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, container, false);
mTwoPane = Objects.requireNonNull(getActivity()).findViewById(R.id.detail_container) != null;
mRecyclerView = view.findViewById(R.id.recyclerView_list);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
mRecyclerView.addItemDecoration(new DividerItemDecoration(Objects.requireNonNull(getContext()), LinearLayout.VERTICAL));
ArrayList<Product> myList = new ArrayList<>();
String[] items = getResources().getStringArray(R.array.product_names);
String[] itemDescriptions = getResources().getStringArray(R.array.product_descriptions);
for (int n = 0; n < items.length; n++){
Product product = new Product();
product.setProductName(items[n]);
product.setFareZone(itemDescriptions[n]);
myList.add(product);
}
mAdapter = new MyListAdapter(getActivity(), myList, mTwoPane);
mRecyclerView.setAdapter(mAdapter);
return view;
}
}
Adapter class
public class MyListAdapter extends RecyclerView.Adapter<MyListAdapter.ProductViewHolder> implements Filterable {
private Context mCtx;
private List<Product> myList;
private List<Product> myListFull;
private boolean mTwoPane;
class ProductViewHolder extends RecyclerView.ViewHolder {
RelativeLayout relativeLayout;
TextView textviewTitle, textviewSubtitle;
ProductViewHolder(View itemView) {
super(itemView);
relativeLayout = itemView.findViewById(R.id.listitem_dualline_relativelayout);
textviewTitle = itemView.findViewById(R.id.listitem_dualline_title);
textviewSubtitle = itemView.findViewById(R.id.listitem_dualline_subtitle);
}
}
public MyListAdapter(Context mCtx, List<Product> myList, boolean mTwoPane) {
this.mCtx = mCtx;
this.myList = myList;
this.mTwoPane = mTwoPane;
myListFull = new ArrayList<>(myList);
}
#NonNull
#Override
public MyListAdapter.ProductViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mCtx);
View v = inflater.inflate(R.layout.listitem_dualline, parent,false);
return new MyListAdapter.ProductViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull final MyListAdapter.ProductViewHolder holder, final int position) {
Log.d(TAG, "onBindViewHolder: called.");
final Product product = myList.get(holder.getAdapterPosition());
holder.textviewTitle.setText(product.getProductName());
holder.textviewSubtitle.setText(product.getProductDescription());
}
#Override
public int getItemCount() {
return myList.size();
}
#Override
public Filter getFilter() {
return exampleFilter;
}
private Filter exampleFilter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
List<Product> filteredList = new ArrayList<>();
if (constraint == null || constraint.length() == 0) {
filteredList.addAll(myListFull);
} else {
String filterPattern = constraint.toString().toLowerCase().trim();
for (Product item : myListFull) {
if (item.getProductName().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
myList.clear();
myList.addAll((List) results.values);
notifyDataSetChanged();
}
};
}

Replace:
myList.addAll((List) results.values);
with:
myList.addAll((List<Product>) results.values);

Try this:
myList.addAll((Collection<? extends Products>) results.values);

Related

Nested RecyclerView OnclickListener to new fragment

**I want to know how to click the items in childRecyclerview show different fragment, I think we should try to modify childAdapter, I am searching for a long time on net. But no use. Please help or try to give some ideas how to achieve this.
hear is my code
**
//workflow fragment
public class WorkflowFragment extends Fragment {
private Context mContext;
private String[] workflowHeading;
private String[] workflowContent;
private int[] imageResourceId;
private RecyclerView recyclerview;
private List<Workflow> workflowList;
private WorkflowAdapter workflowAdapter;
private View view;
public static WorkflowFragment newInstance(String param1, String param2) {
WorkflowFragment fragment = new WorkflowFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
mContext = getActivity();
setHasOptionsMenu(true);
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
if(view==null) {
view = inflater.inflate(R.layout.fragment_workflow, container, false);
}
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
dataInitialize();
recyclerview = view.findViewById(R.id.workflow_recyclerview);
recyclerview.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerview.setHasFixedSize(true);
workflowAdapter =new WorkflowAdapter(getContext(),workflowList);
recyclerview.setAdapter(workflowAdapter);
workflowAdapter.notifyDataSetChanged();
}
private void dataInitialize() {
//list1
List<String> nestedList1 = new ArrayList<>();
nestedList1.add("A");
nestedList1.add("B");
nestedList1.add("C");
nestedList1.add("D");
nestedList1.add("E");
nestedList1.add("F");
nestedList1.add("G");
//list2
List<String>nestedList2 = new ArrayList<>();
nestedList2.add("H");
nestedList2.add("I");
nestedList2.add("G");
nestedList2.add("K");
//list3
List<String>nestedList3 = new ArrayList<>();
nestedList3.add("L");
nestedList3.add("M");
nestedList3.add("N");
nestedList3.add("P");
nestedList3.add("P");
nestedList3.add("Q");
nestedList3.add("R");
nestedList3.add("S");
//list4
List<String>nestedList4 = new ArrayList<>();
nestedList4.add("T");
nestedList4.add("U");
nestedList4.add("V");
nestedList4.add("W");
//list5
List<String>nestedList5 = new ArrayList<>();
nestedList5.add("X");
//list6
List<String>nestedList6 = new ArrayList<>();
nestedList6.add("Y");
nestedList6.add("Z");
workflowList = new ArrayList<>();
workflowList.add(new Workflow("1",nestedList1));
workflowList.add(new Workflow("2",nestedList2));
workflowList.add(new Workflow("3",nestedList3));
workflowList.add(new Workflow("4",nestedList4));
workflowList.add(new Workflow("5",nestedList5));
workflowList.add(new Workflow("6",nestedList6));
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, #NonNull MenuInflater inflater) {
inflater.inflate(R.menu.menu_item,menu);
MenuItem searchItem = menu.findItem(R.id.search_action);
if(searchItem!=null){
SearchView searchView = (SearchView) searchItem.getActionView(); //here stop working
searchView.setMaxWidth(Integer.MAX_VALUE);
searchView.setQueryHint("Search Here!");
searchView.setIconified(false);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
workflowAdapter.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
notifyItemChanged()
workflowAdapter.getFilter().filter(newText);
return false;
}
});
}
super.onCreateOptionsMenu(menu, inflater);
}
}
//ParentAdapter
public class WorkflowAdapter extends RecyclerView.Adapter<WorkflowAdapter.WorkflowViewHolder> implements Filterable{
Context context;
List<Workflow> worflowArrayList;
List<Workflow> worflowArrayListFull;
private List<String>nestedlist = new ArrayList<>();
public WorkflowAdapter(Context context, List<Workflow> worflowArrayList) {
this.context = context;
this.worflowArrayListFull = worflowArrayList;
this.worflowArrayList = new ArrayList<>(worflowArrayListFull);
}
#NonNull
#Override
public WorkflowViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.general_list_item,parent,false);
return new WorkflowViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull WorkflowViewHolder holder, int parentPosition) {
//-get element from your dataset at this position
//-replace the contents of the view with that element
Workflow workflow = worflowArrayList.get(parentPosition);
holder.tvHeading.setText(workflow.getItemText());
//holder.titleImage.setImageResource(model.titleImage);
boolean isExpandable = workflow.isExpandable();
holder.expandableLayout.setVisibility(isExpandable ? View.VISIBLE:View.GONE);
if(isExpandable){
holder.mArrowImage.setImageResource(R.drawable.ic_baseline_arrow_upward_24);
}else{
holder.mArrowImage.setImageResource(R.drawable.ic_baseline_arrow_downward_24);
}
NestedAdapter childAdapter = new NestedAdapter(nestedlist);
holder.nestedRecyclerView.setLayoutManager(new LinearLayoutManager(holder.itemView.getContext()));
holder.nestedRecyclerView.setHasFixedSize(true);
holder.nestedRecyclerView.setAdapter(childAdapter);
holder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
switch(holder.getAdapterPosition()){
case 1:
Toast.makeText(holder.itemView.getContext(), "Item 11 clicked. ", Toast.LENGTH_SHORT).show();
break;
}
workflow.setExpandable(!workflow.isExpandable());
nestedlist = workflow.getNestedList();
notifyItemChanged(holder.getAdapterPosition());
}
});
}
#Override
public int getItemCount() {
return worflowArrayList.size();
}
#Override
public Filter getFilter() {
return workflowFilter;
}
private final Filter workflowFilter = new Filter(){
#Override
protected FilterResults performFiltering(CharSequence constraint) {
ArrayList<Workflow> filteredWorkflowList = new ArrayList<>();
if (constraint == null || constraint.length() == 0){
filteredWorkflowList.addAll(worflowArrayListFull);
}else{
String filterPattern = constraint.toString().toLowerCase().trim();
for (Workflow workflow: worflowArrayListFull){
if(workflow.itemText.toLowerCase().contains(filterPattern))
filteredWorkflowList.add(workflow);
}
}
FilterResults results = new FilterResults();
results.values = filteredWorkflowList;
results.count = filteredWorkflowList.size();
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
worflowArrayList.clear();
worflowArrayList.addAll((ArrayList)results.values);
notifyDataSetChanged();
}
};
public static class WorkflowViewHolder extends RecyclerView.ViewHolder{
private TextView tvHeading;
private LinearLayout linearLayout;
private RelativeLayout expandableLayout;
private ImageView mArrowImage;
private RecyclerView nestedRecyclerView;
public WorkflowViewHolder(#NonNull View itemView) {
super(itemView);
linearLayout=itemView.findViewById(R.id.linear_layout);
expandableLayout=itemView.findViewById(R.id.expandable_layout);
tvHeading = itemView.findViewById(R.id.tvHeading);
mArrowImage=itemView.findViewById(R.id.arro_imageview);
nestedRecyclerView = itemView.findViewById(R.id.child_rv);
}
}
}
//childAdapter
public class NestedAdapter extends RecyclerView.Adapter<com.larntech.myassistant_java.workflow.NestedAdapter.NestedViewHolder> {
private List<String> childItemList; /
public NestedAdapter(List<String> childItemList){
this.childItemList = childItemList;
}
#NonNull
#Override
public com.larntech.myassistant_java.workflow.NestedAdapter.NestedViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.nested_item,parent,false);
return new com.larntech.myassistant_java.workflow.NestedAdapter.NestedViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull com.larntech.myassistant_java.workflow.NestedAdapter.NestedViewHolder holder, int childPosition) {
holder.mTv.setText(childItemList.get(childPosition));
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
switch(holder.getAdapterPosition()){
case 0:
DemoFragment demoFragment =new DemoFragment();
AppCompatActivity activity=(AppCompatActivity) view.getContext();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragment_workflow,demoFragment).addToBackStack(null).commit();
break;
case 1:
FragmentTwo fragmentTwo =new FragmentTwo();
AppCompatActivity activity2=(AppCompatActivity) view.getContext();
activity2.getSupportFragmentManager().beginTransaction().replace(R.id.fragment_workflow,fragmentTwo).addToBackStack(null).commit();
break;
case 2:
Toast.makeText(holder.itemView.getContext(), "Item clicked. ", Toast.LENGTH_SHORT).show();
break;
}
}
});
}
#Override
public int getItemCount() {
return childItemList.size();
}
public class NestedViewHolder extends RecyclerView.ViewHolder{
private TextView mTv;
public NestedViewHolder(#NonNull View itemView) {
super(itemView);
mTv=itemView.findViewById(R.id.nestedItemTv);
}
}
}

RecyclerView Search Filter only filtering one value

I have implemented a Search Filter within my RecyclerView however it only seems to be filtering 1 column of the Array, for example when I type in Banana; the food will filter to Banana, however the calorie figure beside it will only display the value of the first column for Calories.
What could I implement to ensure it filters all columns at the one time, please see code below:
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> implements Filterable {
UserLoginAdapter userLoginAdapter;
private Context context;
private ArrayList<String> FoodID, FoodName, Calories;
private ArrayList<String> FoodNameDuplicate;
private OnItemClickListener mOnItemClickListener;
public interface OnItemClickListener{
public void onItemClick(View view, int position);
}
CustomAdapter(Context context, ArrayList FoodID, ArrayList FoodName, ArrayList Calories, OnItemClickListener onItemClickListener) {
this.context = context;
this.FoodID = FoodID;
this.FoodName = FoodName;
this.Calories = Calories;
FoodNameDuplicate = new ArrayList<>(FoodName);
mOnItemClickListener = onItemClickListener;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.foodrows, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final MyViewHolder holder, int position) {
holder.FoodID.setText(String.valueOf(FoodID.get(position)));
holder.FoodName.setText(String.valueOf(FoodName.get(position)));
holder.Calories.setText(String.valueOf(Calories.get(position)));
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mOnItemClickListener.onItemClick(v, holder.getAdapterPosition());
}
});
}
#Override
public int getItemCount() {
return FoodName.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView FoodID, FoodName, Calories;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
FoodID = itemView.findViewById(R.id.textView_FoodID);
FoodName = itemView.findViewById(R.id.textView_FoodNameTextView);
Calories = itemView.findViewById(R.id.textView_FoodCaloriesTextView);
}
}
#Override
public Filter getFilter() {
return foodFilter;
}
private Filter foodFilter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
ArrayList<String> filteredList = new ArrayList<>();
if(constraint == null || constraint.length() == 0){
filteredList.addAll(FoodNameDuplicate);
} else {
java.lang.String filterPattern = constraint.toString().toLowerCase().trim();
for(String item : FoodNameDuplicate){
if(item.toLowerCase().contains(filterPattern)){
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
FoodName.clear();
FoodName.addAll((ArrayList)results.values);
notifyDataSetChanged();
}
};
}

RecyclerView onClick returns false item

i have a RecyclerView and an EditText, when the search is typed it will filter out the items. but when the search is clicked it just passes the first unfiltered search. here is my code.
here is the FoodAdapter..
public class FoodAdapter extends RecyclerView.Adapter<FoodAdapter.ProductViewHolder> {
private Context mCtx;
private static List<FoodModel> productList;
private OnNoteListener monNoteListener;
//getting the context and product list with constructor
public FoodAdapter(Context mCtx, List<FoodModel> productList, OnNoteListener onNoteListener) {
this.mCtx = mCtx;
this.productList = productList;
this.monNoteListener = onNoteListener;
}
public void filteredList(List<FoodModel> filteredList) {
productList = filteredList;
notifyDataSetChanged();
}
#Override
public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//inflating and returning our view holder
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.sam_layout_products, null);
return new ProductViewHolder(view,monNoteListener);
}
#Override
public void onBindViewHolder(ProductViewHolder holder, int position) {
//getting the product of the specified position
FoodModel product = productList.get(position);
//binding the data with the viewholder views
holder.txtFoodName.setText(product.getFoodName());
holder.txtFoodDesc.setText(product.getFoodDesc());
holder.txtFoodPrice.setText(product.getFoodPrice());
holder.imageView.setImageDrawable(mCtx.getResources().getDrawable(product.getFoodImage()));
}
#Override
public int getItemCount() {
return productList.size();
}
public class ProductViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView txtFoodName, txtFoodDesc, txtFoodPrice;
ImageView imageView;
OnNoteListener onNoteListener;
public ProductViewHolder(View itemView, OnNoteListener onNoteListener) {
super(itemView);
txtFoodName = itemView.findViewById(R.id.txtFood);
txtFoodDesc = itemView.findViewById(R.id.txtFoodDesc);
txtFoodPrice = itemView.findViewById(R.id.txtFoodPrice);
imageView = itemView.findViewById(R.id.imageView);
this.onNoteListener = onNoteListener;
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
onNoteListener.onNoteClick(getAdapterPosition());
}
}
public interface OnNoteListener{
void onNoteClick(int position);
}
}
and here is the activity FoodActivity
public class FoodsActivity extends AppCompatActivity implements FoodAdapter.OnNoteListener {
private DrawerLayout dl;
private ActionBarDrawerToggle t;
private NavigationView nv;
static List<FoodModel> FoodList;
static List<FoodModel> filteredList;
//the recyclerview
RecyclerView recyclerView;
String NameString;
FoodAdapter foodAdapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.foods_layout);
setTitle("Foods");
RecyclerViewFood();
EditText txtFoodSearch = findViewById(R.id.txtFoodSearch);
txtFoodSearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence query, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
SearchFilter(editable.toString());
}
});
}
#Override
public void onNoteClick(int position) {
Intent intent = new Intent(this, sample_layout.class);
intent.putExtra("foods", FoodList.get(position));
startActivity(intent);
}
private void SearchFilter(String text){
recyclerView = (RecyclerView) findViewById(R.id.FoodRecyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
filteredList = new ArrayList<>();
for(FoodModel item: FoodList){
if(item.getFoodName().toLowerCase().contains(text.toLowerCase())){
filteredList.add(item);
}
}
foodAdapter = new FoodAdapter(this,filteredList,this);
// what can i do to pass the correct item to the next intent
recyclerView.setAdapter(foodAdapter);
}
public void RecyclerViewFood() {
recyclerView = (RecyclerView) findViewById(R.id.FoodRecyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
FoodList = new ArrayList<>();
String food_name[] = getResources().getStringArray(R.array.food_name);
String food_desc[] = getResources().getStringArray(R.array.food_desc);
String food_price[] = getResources().getStringArray(R.array.food_price);
int food_image[] = {R.drawable.pic_chickenpizza, R.drawable.pic_dorowot, R.drawable.pic_genfo, R.drawable.pic_kitfo, R.drawable.pic_tibs};
for (int i = 0, j = 0, k = 0, l = 0; i < food_name.length; i++, j++, k++, l++) {
FoodList.add(new FoodModel(2, food_name[i], food_desc[j], food_price[k], food_image[l]));
}
//creating recyclerview adapter
foodAdapter= new FoodAdapter(this, FoodList, this);
//setting adapter to recyclerview
recyclerView.setAdapter(foodAdapter);
}
when the search is entered, it works but when the filteredList is clicked its passing the wrong item to the next intent.
First, your adapter implements Filterable.
public class FoodAdapter extends RecyclerView.Adapter<FoodAdapter.ProductViewHolder> implements Filterable {
// Filtered list
private List<FoodModel> filterList;
// Normal list
private List<FoodModel> productList;
In your constructor:
this.filterList = productList;
productList = new ArrayList<>(productList);
Implementing Filterable requires overriding the getFilter() method.
Filtering the list:
#Override
public Filter getFilter() {
return MyFilter;
}
private Filter MyFilter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
List<FoodModel> filteredList = new ArrayList<>();
if (constraint == null || constraint.length() == 0) {
filteredList.addAll(productList);
} else {
String filterPattern = constraint.toString().trim();
for (FoodModel item : productList) {
if (item.getFoodName().contains(filterPattern)) {
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filterList.clear();
filterList.addAll((List) results.values);
notifyDataSetChanged();
}
};
This is important that you use the filtered list inside onBindViewHolder:
FoodModel product = filterList.get(position);
Now in your activity:
#Override
public void afterTextChanged(Editable editable) {
String newText = editable.toString();
adapter.getFilter().filter(newText);
}
Edit: get size of the filtered list instead of normal list:
#Override
public int getItemCount() {
return filterList.size();
}
In your adapter's onClick:
startMyActivity ( mCtx , filterList.get(getAdapterPosition() ).getId() );
// method
private void startMyActivity ( Activity activity , long id ) {
Intent intent = new Intent( activity , sample_layout.class);
intent.putExtra("foods", id );
activity.startActivity(intent);
}
This is in continuation for the errors you might be facing in #Prince Ali's code. Make these changes to have context passed to your intent
public class ProductViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView txtFoodName, txtFoodDesc, txtFoodPrice;
ImageView imageView;
OnNoteListener onNoteListener;
View mView; //Add this line
public ProductViewHolder(View itemView, OnNoteListener onNoteListener) {
super(itemView);
txtFoodName = itemView.findViewById(R.id.txtFood);
txtFoodDesc = itemView.findViewById(R.id.txtFoodDesc);
txtFoodPrice = itemView.findViewById(R.id.txtFoodPrice);
imageView = itemView.findViewById(R.id.imageView);
this.onNoteListener = onNoteListener;
itemView.setOnClickListener(this);
mView = itemView; // Add this line
}
Now in your onClick method
Context mCtx = holder.mView.getContext();
startMyActivity ( mCtx , filterList.get(getAdapterPosition() ).getId() );
// method
private void startMyActivity ( Context context , long id ) {
Intent intent = new Intent( context , sample_layout.class);
intent.putExtra("foods", id );
context.startActivity(intent);
}
Nevermind, i removed the old setOnClickListener and made a new one in the onBindViewHolder with the following code
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mCtx, sample_layout.class);
intent.putExtra("foods", productList.get(position));
mCtx.startActivity(intent);}
});
and now its working.
thank you all for your answers :)

SearchView doesn´t filter items

Unfortunately, my SeachView does not work. No errors are shown in Android Studio and my app works without any problems. My problem is that when I enter something into the SearchView nothing happens. The Recyclerview still shows all items from my Array List and does not filter them.
Thanks for all the answers :)
Main Activity:
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private ArrayList<Mountain> list;
private SearchView searchView;
private ItemCardViewAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
list = new ArrayList<>();
list.addAll(MountainData.getListData());
showRecyclerViewList();
mAdapter = new ItemCardViewAdapter(this);
mAdapter.setListMountain(list);
searchView = (SearchView) findViewById(R.id.searchView);
searchView.setQueryHint("Search View");
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
mAdapter.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String query) {
mAdapter.getFilter().filter(query);
return false;
}
});
}
private void showRecyclerViewList() {
recyclerView = findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
ItemCardViewAdapter cardViewAdapter = new ItemCardViewAdapter(this);
cardViewAdapter.setListMountain(list);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setAdapter(cardViewAdapter);
}
Adapter:
public class ItemCardViewAdapter extends RecyclerView.Adapter<ItemCardViewAdapter.CardViewHolder> implements Filterable {
private Context context;
private ArrayList<Mountain> listMountain;
private ArrayList<Mountain> filteredList = new ArrayList<>();
public ItemCardViewAdapter(MainActivity context) {
this.context = context;
}
public ArrayList<Mountain> getListMountain() {
return listMountain;
}
public void setListMountain(ArrayList<Mountain> listMountain) {
this.listMountain = listMountain;
}
#NonNull
#Override
public CardViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_cardview, parent, false);
return new CardViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull CardViewHolder holder, final int position) {
holder.tvName.setText(getListMountain().get(position).getName());
holder.tvDescription.setText(getListMountain().get(position).getDescription());
Glide.with(context).load(getListMountain().get(position).getPhoto()).into(holder.imgPhoto);
// intent parcel able to detail
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent detailActivity = new Intent(context, DetailActivity.class);
detailActivity.putExtra(DetailActivity.EXTRA_MOUNTAIN, listMountain.get(position));
context.startActivity(detailActivity);
}
});
}
#Override
public int getItemCount() {
return getListMountain().size();
}
public class CardViewHolder extends RecyclerView.ViewHolder {
ImageView imgPhoto;
TextView tvName, tvDescription;
Button button;
public CardViewHolder(#NonNull View itemView) {
super(itemView);
imgPhoto = itemView.findViewById(R.id.img_card);
tvName = itemView.findViewById(R.id.tv_name_card);
tvDescription = itemView.findViewById(R.id.tv_desc_card);
button = itemView.findViewById(R.id.button);
}
}
#Override
public Filter getFilter(){
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if(charString.isEmpty()){
filteredList = listMountain;
}
else
{
ArrayList<Mountain> MountainFilteredList = new ArrayList<>();
for(Mountain item : listMountain){
if(item.getName().toLowerCase().contains(charString.toLowerCase())) {
MountainFilteredList.add(item);
}
}
filteredList = MountainFilteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = filteredList;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
filteredList = (ArrayList<Mountain>) filterResults.values;
notifyDataSetChanged();
}
};
}
Model:
public class Mountain implements Parcelable {
// create implementation Parcelable to this class
private String name, elevation, photo, description, location;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getElevation() {
return elevation;
}
public void setElevation(String elevation) {
this.elevation = elevation;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public Mountain() {
}
protected Mountain(Parcel in) {
name = in.readString();
elevation = in.readString();
photo = in.readString();
description = in.readString();
location = in.readString();
}
public static final Creator<Mountain> CREATOR = new Creator<Mountain>() {
#Override
public Mountain createFromParcel(Parcel in) {
return new Mountain(in);
}
#Override
public Mountain[] newArray(int size) {
return new Mountain[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(name);
parcel.writeString(elevation);
parcel.writeString(photo);
parcel.writeString(description);
parcel.writeString(location);
}
1) In ItemCardViewAdapter() Constructor you need to pass filteredList into your listMountain list.
public ItemCardViewAdapter(MainActivity context) {
this.context = context;
listMountain= new ArrayList<>();
listMountain.addAll(filteredList);
}
2) firstly, clear listMountain and then add filteredList into listMountain list in publishResults() method.
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
listMountain.clear();
listMountain.addAll((Collection<? extends Mountain>) filterResults.values;
notifyDataSetChanged();
}

Android list filter with RealmObject IllegalStateException [duplicate]

I'm using well RealmRecyclerViewAdapter. My problem is to implement a Filterable that not works. This is the code:
private class AirportAdapter extends RealmRecyclerViewAdapter<AirportR,RecyclerView.ViewHolder> implements Filterable
{
Context context;
OrderedRealmCollection<AirportR>listAirports;
public AirportAdapter(Context activity, OrderedRealmCollection<AirportR>airports)
{
super(activity,airports, true);
this.context = activity;
this.listAirports = airports;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.airport_show, parent,false);
AirportClass holder = new AirportClass(view);
return holder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
AirportR airportR = listAirports.get(position);
AirportClass mHolder = (AirportClass)holder;
mHolder.country.setText(airportR.getIsoCountry());
mHolder.name.setText(airportR.getName());
}
public Filter getFilter()
{
AirportFilter filter = new AirportFilter(this, listAirports);
return filter;
}
private class AirportFilter extends Filter
{
private final AirportAdapter adapter;
OrderedRealmCollection<AirportR>originalList;
OrderedRealmCollection<AirportR>filteredList;
private AirportFilter(AirportAdapter adapter, OrderedRealmCollection<AirportR> originalList)
{
super();
this.adapter = adapter;
this.originalList = originalList;
}
#Override
protected FilterResults performFiltering(CharSequence constraint)
{
filteredList.clear();
final FilterResults results = new FilterResults();
if (constraint.length() == 0)
{
filteredList.addAll(originalList);
}
else
{
final String filterPattern = constraint.toString().toLowerCase().trim();
for (final AirportR airportR : originalList)
{
if (airportR.getName().toLowerCase().contains(filterPattern))
{
filteredList.add(airportR);
}
}
}
results.values = filteredList;
results.count = filteredList.size();
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results)
{
adapter.listAirports.addAll((OrderedRealmCollection<AirportR>) results.values);
adapter.notifyDataSetChanged();
}
}
private class AirportClass extends RecyclerView.ViewHolder
{
TextView name, country;
ImageView image;
public AirportClass(View itemView)
{
super(itemView);
name = (TextView)itemView.findViewById(R.id.name);
country = (TextView)itemView.findViewById(R.id.country);
image = (ImageView)itemView.findViewById(R.id.imageView);
}
}
}
and I give back the error:
java.lang.UnsupportedOperationException: This method is not supported by RealmResults.
at io.realm.RealmResults.addAll(RealmResults.java:710)
at com.example.matteo.downloadairports.fragment.ListAirportFragment$AirportAdapter$AirportFilter.publishResults
how could I save the result after I filter it and update the adapter?
Thanks
Move the filtering to publishResults and use the UI thread Realm's queries to evaluate the new results.
private class AirportAdapter
extends RealmRecyclerViewAdapter<AirportR, RecyclerView.ViewHolder>
implements Filterable {
Realm realm;
public AirportAdapter(Context context, Realm realm, OrderedRealmCollection<AirportR> airports) {
super(context, airports, true);
this.realm = realm;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.airport_show, parent, false);
AirportClass holder = new AirportClass(view);
return holder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
AirportR airportR = getData().get(position);
AirportClass mHolder = (AirportClass) holder;
mHolder.bind(airportR);
}
public void filterResults(String text) {
text = text == null ? null : text.toLowerCase().trim();
RealmQuery<AirportR> query = realm.where(AirportR.class);
if(!(text == null || "".equals(text))) {
query.contains("fieldToQueryBy", text, Case.INSENSITIVE) // TODO: change field
}
updateData(query.findAllAsync());
}
public Filter getFilter() {
AirportFilter filter = new AirportFilter(this);
return filter;
}
private class AirportFilter
extends Filter {
private final AirportAdapter adapter;
private AirportFilter(AirportAdapter adapter) {
super();
this.adapter = adapter;
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
return new FilterResults();
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
adapter.filterResults(constraint.toString());
}
}
private class AirportClass
extends RecyclerView.ViewHolder {
TextView name, country;
ImageView image;
public AirportClass(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.name);
country = (TextView) itemView.findViewById(R.id.country);
image = (ImageView) itemView.findViewById(R.id.imageView);
}
public void bind(AirportR airportR) {
country.setText(airportR.getIsoCountry());
name.setText(airportR.getName());
}
}
}
in your adapter add this it may help you
fun filterResults(text: String?, realm: Realm) {
var text = text
text = text?.toLowerCase()?.trim { it <= ' ' }
val query = realm.where(YourObject::class.java)
if (!(text == null || "" == text)) {
query.contains("username", text, Case.INSENSITIVE).or().contains("username2", text, Case.INSENSITIVE)
}
updateData(query.findAllAsync()) // or findAll()
}

Categories

Resources