I would like to implement a search filter in my adapter class (used in a fragment class showing a list of colors), but although I managed to do it for simpler examples, I don't know how to proceed in this class that receives a json array; I would like to filter the search on the colorCode, since I am not using pojo classes I don't know how to filter just using strings in getFilter() method. Thank you.
Java:
package ...
import...
public class ColorListAdapter extends RecyclerView.Adapter {
private JSONArray colorList;
public ColorListAdapter(JSONArray json){
super();
if(json != null){
this.colorList = json;
}
}
@NonNull @override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.fragment_color_view, viewGroup, false);
return new ColorListHolder(view);
}
@override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
try {
((ColorListHolder)viewHolder).setContentValue(i);
} catch (JSONException e) {
e.printStackTrace();
}
}
@override
public int getItemCount() {
return this.colorList.length();
}
private class ColorListHolder extends RecyclerView.ViewHolder {
private TextView colorCodeText;
private TextView colorNameText;
private CardView imageView;
public ColorListHolder(@NonNull View itemView) {
super(itemView);
this.colorCodeText = itemView.findViewById(R.id.colorCode_text);
this.colorNameText = itemView.findViewById(R.id.colorName_text);
this.imageView = itemView.findViewById(R.id.colorView);
}
public void setContentValue(int index) throws JSONException {
this.colorNameText.setText(((JSONObject)colorList.get(index)).getString("Name"));
this.colorCodeText.setText(((JSONObject)colorList.get(index)).getString("ColorCode"));
this.imageView.setCardBackgroundColor(Color.parseColor(((JSONObject)colorList.get(index)).getString("HexString")));
}
}
}