A trap to be aware of when using managedquery ()

Source: Internet
Author: User

The activity provides a managedquery () method. According to the instructions in the android SDK, "the activity will manage its lifecycle for you. it sounds very good. The activity can manage the life cycle of cursor for you, so you don't have to remember to close (), and the code can be more concise.

But how does the activity manage the life cycle of cursor? Not mentioned in the SDK documentation. Recently, I encountered a bug. In an activity, I used managedquery () to query the database and bound the queried cursor to the listview using the cursoradapter. Then, run the batch delete data table record operation in the activity. Because the time consumption is longer than the duration, multithreading is used. The bug found by the trial team is that during the deletion operation, if you press the Home key, the application will crash. The cause of the crash is that the cursor is released, resulting in an exception in the deletion operation of the working thread.

After reading the source code of activity. Java, we can find out why the crash occurred. Managedquery () is actually nothing more than putting the queried cursor into a group member variable of the activity class. When the activity stops, it will turn off every cursor in the array, and in resume, each cursor in the array is queried again. So after you press the Home key, the activity is stopped and the cursor is closed. If a thread continues to use this cursor, an exception is thrown.

Therefore, when using managedquery (), you need to know when the cursor will be released, and consider that your code will no longer need to use this cursor after the cursor is released.

A trap to be aware of when using managedquery ()

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.