何时关闭SimpleCursorAdapter中使用的Cursor

Axe*_*xel 13 android simplecursoradapter android-cursor searchview

我正在使用SimpleCursorAdapter在ListView中显示结果,但由于我必须在搜索期间(使用SearchView小部件)多次查询我的数据库,因此我担心光标可能会被打开.

这是我查询我的数据库并在ListView中显示结果的方法:

class SearchCustomers extends AsyncTask<String,Void,Cursor>{

        @Override
        protected Cursor doInBackground(String... params) {         
            //get the query
            String query=params[0].toLowerCase(Locale.getDefault());
            Cursor cursor=mDB.searchCustomersByName((query != null ? query : "@@@@"));
            return cursor;

        }

        @Override
        protected void onPostExecute(Cursor result) {           

            if (result != null) {

                String[] from = new String[] { QuickOrderDB.ID,
                        QuickOrderDB.NAME,
                        QuickOrderDB.ADDRESS,
                        QuickOrderDB.PHONE_NUMBER };

                int[] to = new int[] { R.id.customerIDTextView,
                        R.id.customerNameTextView,R.id.customerAddressTextView ,
                        R.id.customerPhoneTextView };

                SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(SearchCustomersActivity.this,
                        R.layout.results_customer_item, result, from, to);
                mResultsListView.setAdapter(cursorAdapter);                 

            }
        }           

    }   
Run Code Online (Sandbox Code Playgroud)

我已经尝试了很多东西来关闭光标,但即使我mResultsListView.setAdapter(cursorAdapter);在结果总是相同之后关闭它:一个空的ListView.

我已经看到了几个问题,其中提到光标将自动关闭,但我想确保这是真的.

有关于此的官方文件吗?SimpleCursorAdapter是否真的自动关闭光标?

提前致谢.

小智 6

  1. 完成后,您需要关闭光标.在setAdapter()调用之后关闭它会阻止适配器访问数据.因此,关闭光标的更好位置是在当前活动中拆除生命周期阶段,例如onPause()或onStop().(onDestroy()不应该被使用,因为Android运行时不保证调用它.我认为最新版本onStop()是保证的)
  2. 我不认为SimpleCursorAdapter适配器会自动自动关闭光标.官方文档提到changeCursor()会 自动关闭旧光标,因此另一个选项可能是在搜索后更改光标. http://developer.android.com/reference/android/widget/CursorAdapter.html#changeCursor(android.database.Cursor)