0

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 by the colorName or colorCode.

Fragment

public class ColorViewFragment extends Fragment {

private RecyclerView recyclerView;
private JSONArray json;
private ColorListAdapter adapter;

private EditText editColor;

@Nullable @Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.color_list, container, false);
    this.recyclerView = view.findViewById(R.id.recyclerView);

    /*
    try {
        this.recyclerView.setAdapter(new ColorListAdapter(this.json));
    } catch (JSONException e) {
        e.printStackTrace();
    }
    */

    try {
        adapter = new ColorListAdapter(json);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    recyclerView.setAdapter(adapter);


    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
    this.recyclerView.setLayoutManager(layoutManager);

    //
    editColor = view.findViewById(R.id.editText);
    editColor.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) {

            ColorViewFragment.this.adapter.getFilter().filter(s);

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });

    return view;
}

public void setJSON(JSONArray newJson){
    this.json = newJson;
}

}

Adapter

public class ColorListAdapter extends RecyclerView.Adapter implements Filterable {

private JSONArray colorList;

private List<String> colorListFiltered = new ArrayList<String>();

public ColorListAdapter(JSONArray json) throws JSONException {
    super();
    if (json != null) {
        this.colorList = json;

            for (int i=0;i<json.length();i++){
                //colorListFiltered.add((colorList.getString(i)));
                colorListFiltered.add(json.getJSONObject(i).getString("Name"));
            }
    }
}


@Override
public Filter getFilter() {
    return new colorFilter();
}


@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.colorListFiltered.size();
}

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(colorListFiltered.get(index));
        //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")));

    }
}


public class colorFilter extends Filter{

    @Override
    protected FilterResults performFiltering(CharSequence constraint) {

        FilterResults Result = new FilterResults();
        // if constraint is empty return the original names

        if(constraint.length() == 0 ) {
            ArrayList<String> arrColorList = new ArrayList<>();
            for (int i = 0; i < colorList.length(); i++) {
                try {
                    arrColorList.add(colorList.getJSONObject(i).getString("Name"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            Result.values = arrColorList;
            Result.count = arrColorList.size();
            return Result;
        }

        /*if(constraint.length() == 0 ){
            Result.values = colorList;
            Result.count = colorList.length();
            return Result;*/

        else {

            List<String> Filtered_Names = new ArrayList<String>();
            String filterString = constraint.toString().toLowerCase();
            String filterableString = "";

            for (int i = 0; i < colorList.length(); i++) {
                try {
                    filterableString = (colorList.getJSONObject(i)).getString("Name");
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                if (filterableString.toLowerCase().contains(filterString)) {
                    Filtered_Names.add(filterableString);
                }
            }

            Result.values = Filtered_Names;
            Result.count = Filtered_Names.size();
            return Result;

        }

    }

    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {

        colorListFiltered = (ArrayList<String>) results.values;
        notifyDataSetChanged();
    }
}

}

Adapter version 2

public class ColorListAdapter extends RecyclerView.Adapter implements Filterable {

private JSONArray colorList;

private ArrayList<ArrayList> colorListFiltered = new ArrayList<>();

ArrayList<String> arrNameList = new ArrayList<>();
ArrayList<String> arrCodeList = new ArrayList<>();
ArrayList<String> arrHexList = new ArrayList<>();

public ColorListAdapter(JSONArray json) throws JSONException {
    super();
    if (json != null) {
        this.colorList = json;

        for (int i = 0; i < json.length(); i++) {

            //colorListFiltered.add((colorList.getString(i)));
            //colorListFiltered.add(json.getJSONObject(i).getString("Name"));

            arrNameList.add((json.getJSONObject(i).getString("Name")));
            arrCodeList.add((json.getJSONObject(i).getString("ColorCode")));
            arrHexList.add((json.getJSONObject(i).getString("HexString")));
            colorListFiltered.add(0, arrNameList);
            colorListFiltered.add(1, arrCodeList);
            colorListFiltered.add(2, arrHexList);

        }
    }
}


@Override
public Filter getFilter() {
    return new colorFilter();
}


@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.colorListFiltered.size();
}

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(colorListFiltered.get(0).get(index).toString());
        this.colorCodeText.setText(colorListFiltered.get(1).get(index).toString());
        this.imageView.setCardBackgroundColor(Color.parseColor(colorListFiltered.get(2).get(index).toString()));


        /*this.colorNameText.setText(colorListFiltered.get(index));
        //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")));*/

    }
}


public class colorFilter extends Filter {

    @Override
    protected FilterResults performFiltering(CharSequence constraint) {

        FilterResults Result = new FilterResults();
        // if constraint is empty return the original names
        ArrayList<ArrayList> arrayLists = new ArrayList<>();

        if (constraint.length() == 0) {
            //ArrayList<String> arrNameList = new ArrayList<>();
            //ArrayList<String> arrCodeList = new ArrayList<>();
            //ArrayList<String> arrHexList = new ArrayList<>();

            for (int i = 0; i < colorList.length(); i++) {
                try {
                    arrNameList.add(colorList.getJSONObject(i).getString("Name"));
                    arrCodeList.add(colorList.getJSONObject(i).getString("HexString"));
                    arrHexList.add(colorList.getJSONObject(i).getString("ColorCode"));
                    arrayLists.add(0, arrNameList);
                    arrayLists.add(1, arrCodeList);
                    arrayLists.add(2, arrHexList);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            Result.values = arrayLists;
            Result.count = arrayLists.size();
            return Result;
        }

        //if(constraint.length() == 0 ){
        //Result.values = colorList;
        //Result.count = colorList.length();
        //return Result;

        else {

            //ArrayList<String> arrNameList = new ArrayList<>();
            //ArrayList<String> arrCodeList = new ArrayList<>();
            //ArrayList<String> arrHexList = new ArrayList<>();

            String filterString = constraint.toString().toLowerCase();
            String filterableString = "";

            for (int i = 0; i < colorList.length(); i++) {
                try {
                    filterableString = (colorList.getJSONObject(i)).getString("Name");
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                if (filterableString.toLowerCase().contains(filterString)) {
                    arrNameList.add(filterableString);
                    try {
                        arrCodeList.add(colorList.getJSONObject(i).getString(("ColorCode")));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    try {
                        arrHexList.add(colorList.getJSONObject(i).getString(("HexString")));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    arrayLists.add(0, arrNameList);
                    arrayLists.add(1, arrCodeList);
                    arrayLists.add(2, arrHexList);

                }
            }

            Result.values = arrayLists;
            Result.count = arrayLists.size();
            return Result;

        }

    }

    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {

        colorListFiltered = (ArrayList<ArrayList>) results.values;
        notifyDataSetChanged();
    }
}

}

1 Answer 1

0

Change the code from get(i) to getJSONObject(i) like below and try.If error is still there then you need to check the logs and post the logs.

for(int i = 0; i<colorList.length(); i++){
                try {
                    filterableString = ((JSONObject) colorList.getJSONObject(i)).getString("Name");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
7
  • It starts filtering, when I press delete to change word, app crashes.
    – mark
    Jul 23, 2019 at 17:30
  • Then instead of passing the JSONArray in the adapter constructor parse JSONArray in ColorViewFragment and add it into the ArrayList like, public ColorListAdapter(ArrayList<String> list){ this.colorList =list}, create one Arraylist of colorList inside adapter instead of JSONArray colorList.
    – Padmini S
    Jul 24, 2019 at 5:14
  • I edited Adapter with help of another guy. Now the list doesn't crash, but items are inverted while I perform filtering. I whink that setContentValue() need to be fixed.
    – mark
    Jul 24, 2019 at 8:01
  • I think this is caused by different indexes of colorListFiltered and colorList.
    – mark
    Jul 24, 2019 at 8:17
  • Maybe I should return also other strings (needed by setcontentValue) in Filter method?
    – mark
    Jul 24, 2019 at 8:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.