How Android cursor is managed automatically

Source: Internet
Author: User

Novice When using the database, it is easy to forget to close the cursor, causing a serious memory leak. Is there any good way to solve this problem? In addition to managing the cursor yourself, what is the way to give the cursor to the system management, without the need to actively close it? Managequery can maintain this cursor for you. Automatically shuts down for you when you exit the activity.

The method Managedquery (Uri, string[], String, string[], string) from the type of Activity is deprecated.

The official Android document is recommended to be replaced with the Cursorloader class.

Let's start by analysing how Managequery manages Cursror.

Private static Final class Managedcursor {        managedcursor (cursor cursor) {            mcursor = cursor;            mreleased = false;            mupdated = false;        }        Private final Cursor mcursor;        Private Boolean mreleased;        Private Boolean mupdated;    }    Private final arraylist<managedcursor> mmanagedcursors =        new arraylist<managedcursor> ();

   Public final Cursor managedquery (Uri Uri, string[] projection, string selection,            string[] Selectionargs, String Sorto Rder) {        Cursor c = getcontentresolver (). Query (URI, projection, selection, Selectionargs, sortOrder);        if (c! = null) {            startmanagingcursor (c);        }        return c;    }
    public void Startmanagingcursor (Cursor c) {        synchronized (mmanagedcursors) {            Mmanagedcursors.add (new Managedcursor (c));        }    }
  protected void OnDestroy () {if (debug_lifecycle) slog.v (TAG, "OnDestroy" + this);        Mcalled = true;        Dismiss any dialogs we is managing.            if (mmanageddialogs! = null) {final int numdialogs = Mmanageddialogs.size ();                for (int i = 0; i < numdialogs; i++) {final Manageddialog MD = mmanageddialogs.valueat (i);                if (md.mDialog.isShowing ()) {Md.mDialog.dismiss ();        }} mmanageddialogs = null;        }//Close any cursors we is managing.            Synchronized (mmanagedcursors) {int numcursors = Mmanagedcursors.size ();                for (int i = 0; i < numcursors; i++) {Managedcursor c = mmanagedcursors.get (i);                if (c! = null) {c.mcursor.close ();        }} mmanagedcursors.clear (); }//Close any open Search dialog if (msearchmanager! =NULL) {Msearchmanager.stopsearch ();    } getapplication (). dispatchactivitydestroyed (this); }

  It seems that these methods are already very clear. After the cursor is encapsulated in a ArrayList, the destroy method of activity is turned off cursor,activity normal destruction must go OnDestroy () method, so that the cursor will be closed. The
Loadermanager method has the following aspects:
1. Startmanagingcursor manages cursors, while Loadermanager manages loader<d> objects. Loader<d> is a template class, and D is a class that contains the data that needs to be loaded. In other words, the data source does not have to be the cursor, it can be list, Jsonarray ... Any class. The Loadermanager is decoupled from the data content it contains, so it is more flexible.
2. Calling Startmanagingcursor causes activity to raise the Requery () method on a cursor that has been added to the management. As mentioned in the first article, it is very expensive to execute the Requery () method on the UI thread. Conversely, the subclass of,loader<d> is asynchronously loaded (translator note: Another thread is called Async. ) data, so using Loadermanager never creates a situation that blocks the UI thread.
3. Startmanagingcursor does not maintain the cursor state when configuration changes, such as portrait-to-landscape switching. The trouble is that each activity due to configuration changes (for example, a simple screen toggle), will cause the cursor next time and be re-queried. Loadermanager is more intelligent, when the configuration changes, it will keep the state of the loader inside it, so there is no need to re-query data. The
4. Loadermanager provides seamless data monitoring. At any time, when the loader data source changes, Loadermanager will receive a new synchronous load of data from the corresponding loader and return the updated data to the client (note: only if loader is implemented correctly, Loadermanager will receive these data change notifications. We will discuss the implementation of the custom loaders in the third article in the series.

Cursorloader managing the cursor with Loadermanager

Use the following method

loadercallbacks<cursor> callback= New  loadercallbacks<cursor> () {               @Override public               Loader <Cursor> oncreateloader (int id, Bundle args) {                      //returns the Cursorloader return you need                      ;              }               @Override public               void onloadfinished (loader<cursor> Loader, Cursor data) {                      //using the Swapcursor () method, So that the old cursor is not closed.                      simplecursoradapter.swapcursor (cursor);              }               @Override public               void Onloaderreset (loader<cursor> Loader) {       ,                       //General write                       Simplecursoradapter.swapcursor (null);              } }; Getloadermanager (). Initloader (0, NULL, callback);

It is important to note that when you use Initloader (), it uses this loader if the loader that specifies the ID already exists. If it does not exist, it will create a new one. But sometimes you want to discard the old and start the new data, using the Restartloader () method.


Welcome to scan QR Code, follow the public number






How Android cursor is managed automatically

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.