Reprint Please specify source: http://blog.csdn.net/l1028386804/article/details/47785491
Do a small project today. Query the phone message information, of course, to the system exposed to the database to query, and later found that there are three ways to choose, the following one by one write out.
1, the way one
In the first way, the Getcontentresolver (). Query () method queries the data in the main thread. This query method is not asynchronous query, directly in the UI thread query data, code such as the following:
Cursor Cursor1 = Getcontentresolver (). Query (Sms.convesation_uri, conversation_projection,null, NULL, "Sms.date desc") ; while (Cursor1.movetonext ()) {log.i ("Cursor1", String.valueof (cursor1.getint (0))); LOG.I ("Cursor1", cursor1.getstring (1)); LOG.I ("Cursor1", cursor1.getstring (2));} Cursor1.close ();
2, Mode two
Another way of querying. Such queries are the same as querying data in the UI thread. Just in this way the cursor does not have to be manually closed, the activity itself will be closed, the cursor is managed by the activity, code such as the following:
Cursor Cursor2 = Managedquery (Sms.convesation_uri, conversation_projection, NULL, NULL, "Sms.date desc"), while ( Cursor2.movetonext ()) {log.i ("Cursor2", String.valueof (cursor2.getint (0))); LOG.I ("Cursor2", cursor2.getstring (1)); LOG.I ("Cursor2", cursor2.getstring (2));}
3, Mode three
The third way to do this is to use the asynchronous query framework provided by Android Asyncqueryhandler,/is an asynchronous query method when a single query is completed. The Onquerycomplete (token, cookie, cursor) is called to notify the query to complete and return the cursor.
The code is as follows:
private void Startquery () {uri uri = sms.convesation_uri;mqueryhandler.startquery (0, NULL, URI, conversation_projection , NULL, NULL, "Sms.date desc");} Write an asynchronous query class private final class Queryhandler extends Asyncqueryhandler {public queryhandler (Contentresolver CR) {Super (CR );} @Overrideprotected void Onquerycomplete (int token, Object cookie, cursor cursor) {super.onquerycomplete (token, Cookie, cursor);//Update Madapter's cursormadapter.changecursor (cursor);}}
Always keep in mind the performance optimization in Android development. So assume that the amount of data is a little bit larger, use an asynchronous query. Try to avoid time-consuming operations in the UI thread, which is best suited for queries that use Android to provide a good asynchronous query framework. In fact, Asyncqueryhandler is also encapsulated handler to achieve. Another point is to use CursorAdapter when querying data from local applications.
Three ways to search for Android--contentresolver