LoaderManager usage (1) --- world before Loader

Source: Internet
Author: User

Source: http://www.androiddesignpatterns.com/2012/07/loaders-and-loadermanager-background.htmlthanks to the efforts of Alex Lockwood, let us see such a wonderful article. The first part is the world before Loader.
This section briefly introduces Loaders and LoaderManager. Section 1 describes how to load data before Android3.0 and points out its defects. Section 2 describes the purpose of each class and its ability to load data asynchronously. This article is the beginning of a series of articles about Loaders and LoaderManager, which are as follows:
I. Loaders World 2: Understanding LoaderManager 3: Implementing Loaders 4: instance: AppListLoader
If you have no idea about Loaders and LoaderManager, you are strongly advised to read the Loaders wizard before continuing to read the guide.
In the past, many applications had defects in response performance before Android3.0. Minor faults between UI switches, activity switching delay, and ANR problems. Most of the failures in response performance come from this fact-most developers execute query operations in the UI thread-loading data in this way is the worst choice.
While this article emphasizes timely feedback, APIs before Android3.0 does not seem to support this feature. Before Loaders, cursors mainly manages and queries through two Activity methods (deprecated is outdated now): public void startManagingCursor (Cursor) tells the activity to manage the life cycle of cursor based on its own life cycle. Cursor is automatically deactivate () when the activity is stopped. Will automatically close () when the activity is destroyed. When the activity stops and restarted again, cursor will re-queried (requery () to query the latest data.
Public Cursor managedQuery (Uri, String, String) This function is used to encapsulate the ContentResolver's query () method. In addition to executing the query, startManagingCursor (cursor) will be called before it returns ). That is to say, the query cursor is put into the activity lifecycle management.
At the same time, when the preceding method executes the query operation in the UI thread, it will cause a serious delay problem. In addition, the "managed cursors" method does not keep data when the activity configuration changes (configuration changed, landscape switching, keyboard pop-up, etc. In these cases, the requry () data will be retried, but it is not necessary and inefficient, and will lead to sluggish and choppy direction switching.
The Managed Cursors issue allows us to simulate the managed cursors issue in a simple code. The Code provided below is to load data in a ListActivity using APIs before Android3.0. This activity queries data from ContentProvider and manages the returned cursor. The query results are packaged with SimpleCursorAdapter and displayed in listview. The code is refined as follows:

public class SampleListActivity extends ListActivity {  private static final String[] PROJECTION = new String[] {"_id", "text_column"};  @Override  protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    // Performs a "managed query" to the ContentProvider. The Activity     // will handle closing and requerying the cursor.    //    // WARNING!! This query (and any subsequent re-queries) will be    // performed on the UI Thread!!    Cursor cursor = managedQuery(        CONTENT_URI,  // The Uri constant in your ContentProvider class        PROJECTION,   // The columns to return for each data row        null,         // No where clause        null,         // No where clause        null);        // No sort order    String[] dataColumns = { "text_column" };    int[] viewIDs = { R.id.text_view };     // Create the backing adapter for the ListView.    //    // WARNING!! While not readily obvious, using this constructor will     // tell the CursorAdapter to register a ContentObserver that will    // monitor the underlying data source. As part of the monitoring    // process, the ContentObserver will call requery() on the cursor     // each time the data is updated. Since Cursor#requery() is performed     // on the UI thread, this constructor should be avoided at all costs!    SimpleCursorAdapter adapter = new SimpleCursorAdapter(        this,                // The Activity context        R.layout.list_item,  // Points to the XML for a list item        cursor,              // Cursor that contains the data to display        dataColumns,         // Bind the data in column "text_column"...        viewIDs);            // ...to the TextView with id "R.id.text_view"    // Sets the ListView's adapter to be the cursor adapter that was     // just created.    setListAdapter(adapter);  }}

The above code has three problems. If you have understood the content above, it is not difficult to understand the first two questions.
1. managedQuery executes a query operation in the Ui thread, which will cause no response from the application. This method should not be used any more. 2. By viewing the Activity. java source code, you can know that managedQuery also calls startManagingCursor to manage the queried data. It looks simple, because we don't need to consider cursor's subsequent shutdown and requery. However, this method causes the data to be re-queried every time the activity status is returned from stopped, which usually causes the UI thread to get stuck. Let the activity manage cursor for us at a greater risk than convenience. 3. The SimpleCursorAdapter constructor of the 32 rows is outdated and should not be used any more. The problem with this constructor is that when there is a change, SimpleCursorAdapter will automatically query. More specifically, CursorAdapter registers a ContentObserver listener on the data, and requeries the data when the monitored data changes. We should use a standard Constructor (if you try to use CursorLoader to load adapter data, make sure that the input value of the last parameter is 0 ). If you cannot understand article 3, it doesn't matter. It's just a small mistake.
Android tablet devices should be released to enhance UI friendliness (faster response ). Larger devices, 7 ~ The 10-inch tablet has more complex applications, more interactions, and more interface la S. Fragment and fragment will be introduced in the future to make the application more dynamic and more event-driven. A simple, single-threaded method to load data is obviously no longer appropriate. So this is the background of the birth of Loader and LoaderManager in Android3.0.
Android3.0, Loaders, and LoaderManager are difficult to manage cursors operations before Honeycomb. For example, normal synchronization in the UI thread ensures that all queries are executed in the background thread in a timely manner. Android3.0 introduces the Loader and LoaderManager classes to simplify this process. You can use the ASL (Android Support Library) to implement these two classes in systems above Android 1.6. The new Loader API is a huge improvement in user experience. Loaders ensures that all cursor operations are asynchronous, thus eliminating the possibility of blocking in the UI thread. In addition, when managed through LoaderManager, Loaders can also maintain the current cursor data in the activity instance, that is, they do not need to re-query (for example, when the activity needs to be restarted due to horizontal and vertical screen switching ). In addition, when data changes, Loaders can intelligently and automatically detect underlying data updates and re-searches.
The conclusion is that the Android Application has become better with the Honeycomb Loaders and Its Implementation library. It is not suitable to use startManagingCursor and managedQuery. It not only slows down your program, but also has the potential of program freezing. On the other hand, Loaders can deliver data loading to a separate background process to significantly improve user experience.

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.