在列表视图中搜索只会刷新整个列表,不会将结果放入列表中

search in listview only refreshes the whole list and does not get the result into list

我正在使用 JSON 从服务器获取数据,当我尝试在列表视图中搜索时,它只是刷新了整个列表,并没有叙述它,但是当我调试时,我可以在 getfilter 上看到结果是对的,它 drugsFiltered = (ArrayList<drugs_json_data>) results.values; 里面确实有过滤后的数据。只有 listview.setadaptor 正在异步任务的 onPostExecute 中完成。

这是我的适配器代码:

public class drugs_adaptor_listView extends ArrayAdapter<drugs_json_data> implements Filterable {

    ArrayList<drugs_json_data> drugs;
    ArrayList<drugs_json_data> drugsFiltered;
    Context context;
    int resource;

    public drugs_adaptor_listView(Context context, int resource, ArrayList<drugs_json_data> drugs) {
        super(context, resource, drugs);
        this.drugs = drugs;
        this.drugsFiltered = drugs;
        this.context = context;
        this.resource = resource;
    }


    @NonNull
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View r = convertView;
        ViewHolder viewHolder;

        if (r == null) {
            LayoutInflater layoutInflater = (LayoutInflater) getContext().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
            r = layoutInflater.inflate(R.layout.row_layout_drugs, null, true);
            viewHolder = new ViewHolder(r);
            r.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) r.getTag();
        }

        drugs_json_data drugs_json_data = getItem(position);
        viewHolder.txtDrugId.setText(drugs_json_data.getDrugId());
        viewHolder.txtDrugName.setText(drugs_json_data.getDrugName());
        viewHolder.txtDrugCategory.setText(drugs_json_data.getDrugCategory());

        Picasso builder = new Picasso.Builder(context).build();
        builder.load(drugs_json_data.getDrugImage()).memoryPolicy(MemoryPolicy.NO_STORE).placeholder(R.drawable.ic_launcher_foreground).into(viewHolder.imageView);

        return r;
    }

    @NonNull
    @Override
    public Filter getFilter() {
        Filter filter = new Filter() {

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

                drugsFiltered = (ArrayList<drugs_json_data>) results.values; // has the filtered values
                if (results.count>0) {
                    notifyDataSetChanged();  // notifies the data with new filtered values
                }else {
                    notifyDataSetInvalidated();
                }
            }

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults results = new FilterResults();        // Holds the results of a filtering operation in values
                ArrayList<drugs_json_data> FilteredArrList = new ArrayList<>();

                if (drugs == null) {
                    drugs = new ArrayList<>(drugsFiltered); // saves the original data in mOriginalValues
                }

                if (constraint == null || constraint.length() == 0) {

                    // set the Original result to return
                    results.count = drugs.size();
                    results.values = drugs;
                } else {
                    constraint = constraint.toString().toLowerCase();
                    for (int i = 0; i < drugs.size(); i++) {
                        String data = drugs.get(i).getDrugName();
                        if (data.startsWith(constraint.toString())) {
                            FilteredArrList.add(new drugs_json_data(drugs.get(i).getDrugId(), drugs.get(i).getDrugName(), drugs.get(i).getDrugCategory(), drugs.get(i).getDrugImage()));
                        }
                    }
                    // set the Filtered result to return
                    results.count = FilteredArrList.size();
                    results.values = FilteredArrList;
                }
                return results;
            }
        };
        return filter;
    }

    class ViewHolder {
        TextView txtDrugId, txtDrugName, txtDrugCategory;
        ImageView imageView;

        ViewHolder(View v) {
            txtDrugId = v.findViewById(R.id.txtDrugId);
            txtDrugName = v.findViewById(R.id.txtDrugName);
            txtDrugCategory = v.findViewById(R.id.txtDrugCat);
            imageView = v.findViewById(R.id.ImageViewDrug);
        }
    }
}

这里是数据模型:

public class drugs_json_data {
    private String drugImage;
    private String drugName;
    private String drugCategory;
    private String drugId;

    public drugs_json_data(String drugImage, String drugName, String drugCategory, String drugId) {
        this.drugImage = drugImage;
        this.drugName = drugName;
        this.drugCategory = drugCategory;
        this.drugId = drugId;
    }

    public String getDrugImage() {
        return this.drugImage;
    }

    public void setDrugImage(String drugImage) {
        this.drugImage = drugImage;
    }

    public String getDrugName() {
        return this.drugName;
    }

    public void setDrugName(String drugName) {
        this.drugName = drugName;
    }

    public String getDrugCategory() {
        return this.drugCategory;
    }

    public void setDrugCategory(String drugCategory) {
        this.drugCategory = drugCategory;
    }

    public String getDrugId() {
        return this.drugId;
    }

    public void setDrugId(String drugId) {
        this.drugId = drugId;
    }
}

这是主要的 activity 代码:

public class clerk_drugs extends AppCompatActivity {

    ListView listView;
    Button createDrug;
    String drug_id, json_drug;
    TextView noMed;
    EditText searchTxt;
    JSONObject jsonObject;
    JSONArray jsonArray;
    ArrayList<drugs_json_data> arrayList;
    drugs_adaptor_listView adapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_clerk_drugs);
        createDrug = findViewById(R.id.create_drug);
        arrayList = new ArrayList<>();
        listView = findViewById(R.id.list_drugs);
        noMed = findViewById(R.id.no_med);
        searchTxt = findViewById(R.id.listSearch);
        searchTxt.setSingleLine(true);

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    new ReadJSON().execute("http://(mylink)").get();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        try {
            jsonObject = new JSONObject(json_drug);
            jsonArray = jsonObject.getJSONArray("server_response");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                drug_id = ((TextView) view.findViewById(R.id.txtDrugId)).getText().toString();

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

                        JSONObject jobj = jsonArray.getJSONObject(i);
                        String drugid = jobj.getString("drug_id");
                        if(drugid.equals(drug_id)) {
                            String drugname = jobj.getString("drug_name");
                            String drugcategory = jobj.getString("drug_category");
                            String drugdescription = jobj.getString("drug_description");
                            String drugphoto = jobj.getString("drug_photo");

                            drug_update_dialog drug_update_dialog = new drug_update_dialog();
                            Bundle args = new Bundle();
                            args.putString("drug-id", drug_id);
                            args.putString("drug-name", drugname);
                            args.putString("drug-category", drugcategory);
                            args.putString("drug-description", drugdescription);
                            args.putString("drug_photo",drugphoto);

                            drug_update_dialog.setArguments(args);
                            drug_update_dialog.show(getSupportFragmentManager(),"ویرایش اطلاعات دارو");
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        searchTxt.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) {
                 adapter.getFilter().filter(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        searchTxt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(!hasFocus){
                    hideKeyboard(v);
                }
            }
        });

    }

    public void hideKeyboard(View view) {
        InputMethodManager inputMethodManager =(InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    class ReadJSON extends AsyncTask<String, Integer, String>{

        @Override
        protected String doInBackground(String... params) {
            return readURL(params[0]);
        }

        @Override
        protected void onPostExecute(String content) {
            try {
                JSONObject jsonObject = new JSONObject(content);
                JSONArray jsonArray = jsonObject.getJSONArray("server_response");
                for(int i=0; i<jsonArray.length();i++){
                    JSONObject drugObj = jsonArray.getJSONObject(i);
                    arrayList.add(new drugs_json_data(
                            drugObj.getString("drug_photo"),
                            drugObj.getString("drug_name"),
                            drugObj.getString("drug_category"),
                            drugObj.getString("drug_id")

                    ));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            adapter = new drugs_adaptor_listView(
                    getApplicationContext(), R.layout.row_layout_drugs, arrayList
            );

            listView.setAdapter(adapter);
            listView.setTextFilterEnabled(true);

            if (adapter.getCount()==0){
                noMed.setVisibility(View.VISIBLE);
            }
        }
    }


    private String readURL(String theURL) {

        StringBuilder content = new StringBuilder();

        try{
            URL url = new URL(theURL);
            URLConnection urlConnection = url.openConnection();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String line;

            while((line=bufferedReader.readLine())!=null){
                content.append(line).append("\n");
            }
            bufferedReader.close();

        }catch (Exception e){
            e.printStackTrace();
        }
        json_drug = content.toString();
        return content.toString();
    }

    @Override
    public void onBackPressed() {
        finish();
        Intent intent = new Intent(this,patient_mainPage.class);
        startActivity(intent);
    }

    public void createDrugDialog(View view){
        openDrugDialog();
    }

    private void openDrugDialog() {
        drug_add_dialog drug_add_dialog = new drug_add_dialog();
        drug_add_dialog.show(getSupportFragmentManager(),"ثبت داروی جدید");
    }

}

如果有人能提供帮助,我将不胜感激。

已更新

getView方法中适配器

替换

 drugs_json_data drugs_json_data = getItem(position);

drugs_json_data drugs_json_data = drugsFiltered.get(position);