我正在运行异步任务以从服务器加载结果。我正在使用 SearchView 传递查询词。然后使用我自己的 API 来获取数据。我很困惑为什么 AsyncTask 输出数据两次。

 mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(final String query) {
            linearLayout.removeAllViews();
            new Search(query, linearLayout).execute();

            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            linearLayout.removeAllViews();
            return false;
        }
    });




private class Search extends AsyncTask<Void, Void, ArrayList<Business>> {

    String query;
    LinearLayout linearLayout;

    public Search(String query, LinearLayout linearLayout) {
        this.query = query;
        this.linearLayout = linearLayout;
    }

    @Override
    protected ArrayList<Business> doInBackground(Void... params) {
        YelpApi yelpApi = new YelpApi(getString(R.string.yelp_consumer_key), getString(R.string.yelp_consumer_secret), getString(R.string.yelp_token), getString(R.string.yelp_token_secret));
        HashMap<String, String> parameters = new HashMap<>();
        parameters.put("term", query);
        parameters.put("sort", "2");
        parameters.put("limit", "5");
        return yelpApi.searchLocation("North Hills, CA", parameters);
    }

    @Override
    protected void onPostExecute(ArrayList<Business> businesses) {
        for (int i = 0; i < businesses.size(); i++) {
            TextView mTextView = new TextView(getApplicationContext());
            mTextView.setText(businesses.get(i).getName());
            mTextView.setTextColor(Color.BLACK);
            linearLayout.addView(mTextView);
        }
    }
}

但是,当我运行搜索时,会显示数据的两个实例。我无法弄清楚我做错了什么。

最佳答案

将您的查询搜索监听器更改为类似

 mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(final String query) {
            linearLayout.removeAllViews();
            new Search(query, linearLayout).execute();

            return true;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            linearLayout.removeAllViews();
            return false;
        }
    });
的内容
希望它会起作用

10-07 19:46