loader的简单使用过程分析
首先,fragment或者activity必须实现callback接口
必须实现的三个方法为
public Loader<Cursor> onCreateLoader(int id, Bundle args)
public void onLoadFinished(Loader<Cursor> loader, Cursor data)
public void onLoaderReset(Loader<Cursor> loader)
其次,在使用getloadermanager().initLoader(id,data,callback)
来开始这个过程
下面是使用实例,异步获取联系人信息,加载到list上面
package com.example.u3.actionbartest2; import android.app.Fragment; import android.app.ListFragment; import android.app.LoaderManager; import android.content.CursorLoader; import android.content.Loader; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.provider.ContactsContract; import android.text.AndroidCharacter; import android.widget.SimpleCursorAdapter; /** * Created by U3 on 2015/3/10. */ public class TestFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor>{ private SimpleCursorAdapter madapter; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); madapter = new SimpleCursorAdapter(getActivity(), android.R.layout.activity_list_item,null,new String[]{ContactsContract.Contacts.DISPLAY_NAME,ContactsContract.Contacts.CONTACT_STATUS},new int[]{android.R.id.text1,android.R.id.text2},0); setListAdapter(madapter); getLoaderManager().initLoader(0,null,this); } static final String[] CONTACTS_SUMMARY_PROJECTION = new String[] { ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.Contacts.CONTACT_STATUS, // ContactsContract.Contacts.CONTACT_PRESENCE, // ContactsContract.Contacts.PHOTO_ID, // ContactsContract.Contacts.LOOKUP_KEY, }; @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { Uri uri; uri = ContactsContract.Contacts.CONTENT_URI; String select = "(("+ContactsContract.Contacts.DISPLAY_NAME+" NOTNULL) AND ("+ ContactsContract.Contacts.HAS_PHONE_NUMBER +"=1) AND ("+ ContactsContract.Contacts.DISPLAY_NAME +" != ''))"; /*String select = "((" + ContactsContract.Contacts.DISPLAY_NAME + " NOTNULL) AND (" + ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1) AND (" + ContactsContract.Contacts.DISPLAY_NAME + " != '' ))";*/ return new CursorLoader(getActivity(),uri,CONTACTS_SUMMARY_PROJECTION,select,null,null); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { madapter.swapCursor(data); } @Override public void onLoaderReset(Loader<Cursor> loader) { madapter.swapCursor(null); } }
-----人若无名,则可专心练剑