java - 在解析 json 数组的适配器类中实现搜索过滤器(不使用 pojo)

标签 java android

我想在我的适配器类中实现一个搜索过滤器(在显示颜色列表的 fragment 类中使用),但是尽管我设法为更简单的示例做到这一点,但我不知道如何在此类中继续接收一个 json 数组;我想按 colorName 或 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;
}

}

适配器

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) ,如下所示并尝试。如果错误仍然存​​在,那么您需要检查日志并发布日志。

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

关于java - 在解析 json 数组的适配器类中实现搜索过滤器(不使用 pojo),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57134956/

相关文章:

java - Spring JPA : External database configuration from property file does not work

java - Controller 类中的 Spring MVC 本地化不起作用

android - 如何在 Java 代码中选择 ListView Item?

java - 如何在 Java 中调用 Kotlin 类键?

Android:PhoneStateListener 在服务中不工作

android - PANIC : Missing emulator engine program for 'x86' CPU. [Ionic Cordova 运行 android]

java - GridView -NullPointerException 错误 - 尝试访问 "child imageview"

java - 类加载器设置不适用于 Websphere 8

java - 大 O 表示法-请解释 O(log2n)

android - 自定义 RecyclerClickListener 无法针对多个 onClicks 正常工作