AsyncTask:onPostExecute运行两次?

时间:2015-08-07 06:28:16

标签: java android android-asynctask

我正在运行异步任务来从服务器加载结果。我正在使用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);
        }
    }
}

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

1 个答案:

答案 0 :(得分:2)

将您的查询搜索列表器更改为此类

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

希望它能运作