在解析json数组的Adapter类中实现搜索过滤器(不使用pojo) [英] Implementing Search Filter in Adapter Class which parses a json array (without using pojo)

查看:24
本文介绍了在解析json数组的Adapter类中实现搜索过滤器(不使用pojo)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的适配器类(用于显示颜色列表的片段类中)中实现搜索过滤器,但是尽管我设法为更简单的示例完成了该操作,但我不知道如何在此类中进行接收一个json数组;我想按colorName或colorCode过滤搜索.

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.

片段

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;
}

}

适配器

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();
    }
}

}

适配器版本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();
    }
}

}

推荐答案

将代码从get(i)更改为getJSONObject(i),如下所示,然后尝试.如果错误仍然存​​在,则需要检查日志并发布日志.

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();
                }

这篇关于在解析json数组的Adapter类中实现搜索过滤器(不使用pojo)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆