▼Androidメモ▼
ローダー


ローダーを利用するプログラムを作成する。



ソースコード
LoaderEx.java
package net.npaka.loaderex;
import android.app.Activity;
import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract.Contacts;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

//ローダー
public class LoaderEx extends Activity implements 
    LoaderManager.LoaderCallbacks<Cursor> {
    private SimpleCursorAdapter cursorAdapter;
    
    //アクティビティ生成時に呼ばれる
    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);

        //リストビューの設定
        ListView listView=new ListView(this);
        listView.setScrollingCacheEnabled(false);
        cursorAdapter=new SimpleCursorAdapter(this,
            android.R.layout.simple_list_item_2,null,
            new String[]{Contacts.DISPLAY_NAME,Contacts.CONTACT_STATUS},
            new int[] {android.R.id.text1,android.R.id.text2},0);
        listView.setAdapter(cursorAdapter);        
        setContentView(listView);
        
        //ローダーの初期化
        getLoaderManager().initLoader(0,null,this);
    }

    //ローダー生成時に呼ばれる
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        String select="(("+Contacts.DISPLAY_NAME+" NOTNULL) AND ("+
            Contacts.HAS_PHONE_NUMBER+"=1) AND ("+
            Contacts.DISPLAY_NAME+" != '' ))";
        String[] projection=new String[] {
            Contacts._ID,
            Contacts.DISPLAY_NAME,
            Contacts.CONTACT_STATUS,
            Contacts.CONTACT_PRESENCE,
            Contacts.PHOTO_ID,
            Contacts.LOOKUP_KEY};
        return new CursorLoader(this,Contacts.CONTENT_URI,
            projection,select,null,
            Contacts.DISPLAY_NAME+" COLLATE LOCALIZED ASC");
    }

    //ロード完了時に呼ばれる
    public void onLoadFinished(Loader<Cursor> loader,Cursor data) {
        cursorAdapter.swapCursor(data);
    }
    
    //ローダーリセット時に呼ばれる
    public void onLoaderReset(Loader<Cursor> loader) {
        cursorAdapter.swapCursor(null);
    }
}

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="net.npaka.loaderex"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="14" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />
    
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".LoaderEx" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>



−戻る−