When to close Cursor used in SimpleCursorAdapter

浪尽此生 提交于 2019-12-04 00:01:28
Gvancha
  1. You need to close your cursor once you are done with it. Closing it after setAdapter() call would prevent the adapter from accessing the data. Hence a better place to close the cursor would be during current activities tear down life cycle stages such as onPause() or onStop(). (onDestroy() should not be used as Android run-time does not guarantee calling it. I think on latest version onStop() is guaranteed)
  2. I don't think SimpleCursorAdapter adapter automatically closes the cursor automatically. The official document mentions that changeCursor() automatically closes the old cursor, so another option could be to change your cursor after search. http://developer.android.com/reference/android/widget/CursorAdapter.html#changeCursor(android.database.Cursor)

It's better if you get the Cursor using a CursorLoader instead of an AsyncTask. The Loaders are synched to the Activity/Fragment lifecycle via the LoaderManager, and the system will close the Cursor provided by the CursorLoader automatically for you when it's needed.

You should close the cursor in your fragment or activity's onPause() callback. After the activity is paused it's possible that older Android systems will delete the app to free memory.

This implies that you need to reestablish the cursor in the corresponding onResume() callback.

Don't create a variable for the cursor, just add the db query directly into the constructor as the argument c, db.query() or a method that holds the desired query), this seems to work.

SimpleCursorAdapter (Context context, 
                int layout, 
                Cursor c, 
                String[] from, 
                int[] to, 
                int flags)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!