星期五, 8月 22, 2014

Loader (二)

Using the LoaderManager Callbacks

LoaderManager.LoaderCallbacks是一個回調介面讓使用者能與LoaderManager互動。

Loader,尤其是CursorLoader,預期在停止後保留它們的資料。這允許應用程式保留住它們的資料跨越activity或fragment的onStop()及onStrat()方法,以便當使用者回到應用程式,他們不需要等待資料重新載入。你可以使用LoaderManager.LoaderCallbacks方法知道何時建立新的loader,並告訴應用程式何時該停止使用loader的資料。

LoaderManager.LoaderCallbacks包含這些方法

  • onCreateLoader() - 為特定ID建立及回傳新的loader
  • onLoaderFinished() - 當先前建立的loader完成資料加載時呼叫
  • onLoaderReset() - 當先前建立的loader被重置時呼叫,從而使得其資料不可用

onCreateLoader

當你試著存取loader時(例如,透過initLoader()),它會檢查特定ID的loader是否存在。如果不存在,它會觸發LoaderManager.Loadercallbacks方法的onCreateLoader()方法,這是建立新loader的地方,通常會是CursorLoader,但是你可以執行你自己的loader子類。

在此例中,這個onCreateLoader()方法會建立一個CursorLoader,你必須使用建構子建立CursorLoader,建構子需要完整的資訊去查詢Content Provider。具體來說,建構子需要以下資訊
  • uri - 對於要取得content的URI
  • projection - 哪些columns回傳的列表,傳入null將會回傳所有columns,這樣是無效率的
  • selection - 過濾器宣告回傳哪些rows,格式如SQL WHERE條文(排除WHERE本身)。傳入null會回傳特定uri的所有rows
  • selectionArgs - 在selection中可能會包含多個?s,這將從selectionArgs的值取代,依它們在selection出現的順序。這些值被用字串綁定
  • sortOrder - 如何指揮rows,格式為SQL ORDER BY條文(排除ORDER BY本身)。傳入null使用預設的排序方式,它可能沒有排序
舉例

// If non-null, this is the current filter the user has provided.
String mCurFilter;
...
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    // This is called when a new Loader needs to be created.  This
    // sample only has one Loader, so we don't care about the ID.
    // First, pick the base URI to use depending on whether we are
    // currently filtering.
    Uri baseUri;
    if (mCurFilter != null) {
        baseUri = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI,
                  Uri.encode(mCurFilter));
    } else {
        baseUri = Contacts.CONTENT_URI;
    }

    // Now create and return a CursorLoader that will take care of
    // creating a Cursor for the data being displayed.
    String select = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND ("
            + Contacts.HAS_PHONE_NUMBER + "=1) AND ("
            + Contacts.DISPLAY_NAME + " != '' ))";
    return new CursorLoader(getActivity(), baseUri,
            CONTACTS_SUMMARY_PROJECTION, select, null,
            Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
}


onLoadFinished

此方法當先前loader已經完成加載資料時被呼叫,此方法保證在最後供應給loader的資料釋放之前被呼叫。在此刻,你應該移除所有使用的舊資料,但不應該自己完成釋放資料,因為擁有資料的loader會照料它們。

一旦loader知道應用程式不會在使用資料,loader就會釋放資料。例如,如果資料是來自CursorLoader的cursor,你不應該呼叫close()。如果此cursor被放入CursorAdapter,你應該使用SwapCursor()方法,如此舊的cursor不會被關閉。

舉例

// This is the Adapter being used to display the list's data.
SimpleCursorAdapter mAdapter;
...
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    // Swap the new cursor in.  (The framework will take care of closing the
    // old cursor once we return.)
    mAdapter.swapCursor(data);
}


onLoaderReset

當先前的loader被重置時會呼叫此方法,如此使資料為不可用的。此回調方法讓你找出資料和時被釋放,如此你可以移除你的參考。

以下執行為swapCursor()方法,傳入參數為null

// This is the Adapter being used to display the list's data.
SimpleCursorAdapter mAdapter;
...
public void onLoaderReset(Loader<Cursor> loader) {
    // This is called when the last Cursor provided to onLoadFinished()
    // above is about to be closed.  We need to make sure we are no
    // longer using it.
    mAdapter.swapCursor(null);
}


Example

以下例子為在Fragment上用ListView顯示查詢聯絡人content provider的結果,使用CursorLoader管理作用在proivder的查詢。

為了讓應用程式存取使用者的聯絡人資料,它的manifest必須包含權限READ_CONTACTS。

public static class CursorLoaderListFragment extends ListFragment
        implements OnQueryTextListener, LoaderManager.LoaderCallbacks<Cursor> {

    // This is the Adapter being used to display the list's data.
    SimpleCursorAdapter mAdapter;

    // If non-null, this is the current filter the user has provided.
    String mCurFilter;

    @Override public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        // Give some text to display if there is no data.  In a real
        // application this would come from a resource.
        setEmptyText("No phone numbers");

        // We have a menu item to show in action bar.
        setHasOptionsMenu(true);

        // Create an empty adapter we will use to display the loaded data.
        mAdapter = new SimpleCursorAdapter(getActivity(),
                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);
        setListAdapter(mAdapter);

        // Prepare the loader.  Either re-connect with an existing one,
        // or start a new one.
        getLoaderManager().initLoader(0, null, this);
    }

    @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // Place an action bar item for searching.
        MenuItem item = menu.add("Search");
        item.setIcon(android.R.drawable.ic_menu_search);
        item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
        SearchView sv = new SearchView(getActivity());
        sv.setOnQueryTextListener(this);
        item.setActionView(sv);
    }

    public boolean onQueryTextChange(String newText) {
        // Called when the action bar search text has changed.  Update
        // the search filter, and restart the loader to do a new query
        // with this filter.
        mCurFilter = !TextUtils.isEmpty(newText) ? newText : null;
        getLoaderManager().restartLoader(0, null, this);
        return true;
    }

    @Override public boolean onQueryTextSubmit(String query) {
        // Don't care about this.
        return true;
    }

    @Override public void onListItemClick(ListView l, View v, int position, long id) {
        // Insert desired behavior here.
        Log.i("FragmentComplexList", "Item clicked: " + id);
    }

    // These are the Contacts rows that we will retrieve.
    static final String[] CONTACTS_SUMMARY_PROJECTION = new String[] {
        Contacts._ID,
        Contacts.DISPLAY_NAME,
        Contacts.CONTACT_STATUS,
        Contacts.CONTACT_PRESENCE,
        Contacts.PHOTO_ID,
        Contacts.LOOKUP_KEY,
    };
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        // This is called when a new Loader needs to be created.  This
        // sample only has one Loader, so we don't care about the ID.
        // First, pick the base URI to use depending on whether we are
        // currently filtering.
        Uri baseUri;
        if (mCurFilter != null) {
            baseUri = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI,
                    Uri.encode(mCurFilter));
        } else {
            baseUri = Contacts.CONTENT_URI;
        }

        // Now create and return a CursorLoader that will take care of
        // creating a Cursor for the data being displayed.
        String select = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND ("
                + Contacts.HAS_PHONE_NUMBER + "=1) AND ("
                + Contacts.DISPLAY_NAME + " != '' ))";
        return new CursorLoader(getActivity(), baseUri,
                CONTACTS_SUMMARY_PROJECTION, select, null,
                Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
    }

    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        // Swap the new cursor in.  (The framework will take care of closing the
        // old cursor once we return.)
        mAdapter.swapCursor(data);
    }

    public void onLoaderReset(Loader<Cursor> loader) {
        // This is called when the last Cursor provided to onLoadFinished()
        // above is about to be closed.  We need to make sure we are no
        // longer using it.
        mAdapter.swapCursor(null);
    }
}



Loader (一)

Loader讓異步加載資料到Activity或Fragment更加容易,loaders有以下特點
  • 它們是提供給每個Activity或Fragment用的
  • 它們提供異步的資料加載
  • 它們監測資料來源並在內容改變時傳送新的結果
  • 當Cursor更改設定正在重建時,它們會自動地重新連接最後的loader的Cursor,所以他們不需重新查詢它們的數據。
Using Loader in an Application

如何在應用程式中使用Loader,應用程式典型地使用loader包含以下
  • 一個Activity或Fragment
  • 一個LoaderManager的實例
  • 一個CursorLoader藉由ContentProvider加載資料。另外,可以執行自己的Loader或AsyncTaskLoader的子類從其他資料來源加載。
  • 執行LoaderManager.LoaderCallbacks,這是產生新Loader及管理參考到已存在的Loader的地方
  • 顯示Loader資料的方法,如SimpleCursorAdapter
  • 一個資料來源,如ContentProvider,當使用一個CursorLoader

Starting a Loader

LoaderManager管理在Activity或Fragment一個或多個Loaders,每個Activity或Fragment只能有一個Loader。

初始化Loader典型方式是在Activity的onCreate()方法或是Fragment中的onActivityCreate()方法,以下

// Prepare the loader.  Either re-connect with an existing one,
// or start a new one.
getLoaderManager().initLoader(0, null, this);

initLoader()方法傳入的參數為
  • 唯一的識別碼用來識別loader,此例中,ID為0
  • 可選的參數在建構時提供loader(此例中為null)
  • 一個LoaderManager.Loadercallbacks的實施,LoaderManager呼叫報告loader事件,此例中,本地類別實施LoaderManager.LoaderCallback介面,所以傳入this參考到自己
initLoader()方法呼叫確保loader被初始化與活躍,它有兩種可能的結果

  • 如果指定給loader的ID已存在,重複使用最後建立的loader
  • 如果指定給loader的ID不存在,initLoader()方法會觸發LoaderManager.LoaderCallbacks方法的onCreateLoader(),這是執行程式去實例及回傳新loader的地方
在任一情況下,特定的LoaderManager.LoaderCallbacks實施是與loader關聯的,且在loader狀態改變時被呼叫。如果在呼叫的當下呼叫者在其開始狀態,並且請求的loader已存在且產生了資料,系統會立即呼叫onLoadFinish(),所以必須準備這樣的情況發生。

注意initLoader()方法會回傳被建立的Loader,但你不需要取得一個參考給它,LoaderManager會自動地管理loader的生命週期,必要時刻LoaderManager會啟動和停止加載,並維護loader的狀態及其關聯的資料。這意味著,你很少直接與loader互動。當特別的事件發生時,你一般必須使用LoaderManager.LoaderCallbacks方法去干預加載的程序。


Restarting a Loader

當你使用initLoader()方法時,如果指定ID有以存在的loader,它會使用已存在的loader;如果沒有,他會建立一個。但是有時候想要拋棄舊資料並重新開始。

拋棄舊資料,使用restartLoader()。例如,SearchView.OnQueryTextListener在使用者的查詢改變時重新開始loader,loader需要重新開始,如此它才能使用被修訂的搜尋過濾器去做新的查詢。

public boolean onQueryTextChanged(String newText) {
    // Called when the action bar search text has changed.  Update
    // the search filter, and restart the loader to do a new query
    // with this filter.
    mCurFilter = !TextUtils.isEmpty(newText) ? newText : null;
    getLoaderManager().restartLoader(0, null, this);
    return true;
}





星期四, 8月 21, 2014

Building Layouts with an Adapter

當內容對於你的layout來說是動態的或事先無法決定的,你可以使用AdapterView在執行中填充layout。AdapterView類別的子類運用一個Adapter將資料綁定在Layout上。Adapter扮演中介的角色介於資料來源與AdapterView layout之間,Adapter取出資料(從陣列或資料庫查詢等來源),並轉換每個輸入為一個view加到AdapterView layout中。

常見有Adapter的Layout有
  • ListView
  • GridView
Filling an adapter view with data

你可以藉由將AdapterView實例綁定一個Adapter來填充AdapterView如ListView或GridView,Adapter會從外部來源取出資料並為每一個輸入建立一個View。

Android提供許多Adapter的子類用來取出不同種類的資料,兩種最常見的Adapter是ArrayAdapter和SimpleCusorAdapter。


ArrayAdapter

當資料來源是陣列時使用ArrayAdapter。預設的情況下,ArrayAdapter藉由在每個陣列項目上呼叫toString()並把內容放入TextView中為每個陣列項目建立view。

例如,如果你有一個字串陣列想顯示在ListView上,利用建構子傳入對於每個字串的layout和字串陣列來初始化一個新的ArrayAdapter。
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
        android.R.layout.simple_list_item_1, myStringArray);
此建構子的參數包含
  • 你的app的Context
  • 供陣列中每個字串的Layout,包含了一個TextView
  • 字串陣列
然後簡單地在ListView上呼叫setAdapter():
ListView listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(adapter);
可以複寫toString()來客製化每個陣列項目的外觀,或是可以為每個陣列項目建立不同於TextView的view(例如ImageView),繼承ArrayAadapter類別複寫getView()方法回傳想供給每個陣列項目的類型。


SimpleCursorAdapter

當資料來自Cursor時使用SimpleCursorAdapter。使用SimpleCursorAdapter時,必須指定一個layout給在Cursor的每一個row且每個columns應該被插入layout中的view。例如,想要建立一個人名和電話的列表,可以執行的一個查詢回傳Cursor,包含一個row為一個人,columns為人名和電話,接著建立一個字串陣列指定從Cursor中的哪個Column是想在Layout中的及建立一個整數陣列指定每個column相對應的view。
String[] fromColumns = {ContactsContract.Data.DISPLAY_NAME,
                        ContactsContract.CommonDataKinds.Phone.NUMBER};
int[] toViews = {R.id.display_name, R.id.phone_number};
當你建立SimpleCursorAdapter實例,傳入layout、Cursor、這兩個陣列。
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
        R.layout.person_name_and_number, cursor, fromColumns, toViews, 0);
ListView listView = getListView();
listView.setAdapter(adapter);
如果你的應用程式在生命週期中,改變了油Adapter讀取的數據,應該呼叫notifyDataSetChanged()方法,這將通知你的view,數據已經改變,應該刷新本身。


Handing click events

可以藉由執行AdapterView.onItemClickListener介面回應在AdapterView中的每個項目。

// Create a message handling object as an anonymous class.
private OnItemClickListener mMessageClickedHandler = new OnItemClickListener() {
    public void onItemClick(AdapterView parent, View v, int position, long id) {
        // Do something in response to the click
    }
};

listView.setOnItemClickListener(mMessageClickedHandler);



星期五, 6月 29, 2012

Sensor (三)

Android應用程式學習筆記

Motion Sensors

Android平台提供好幾個感應器讓我們監測裝置的運動,這些感應器中有些是以硬體為基礎感應產生數據,有些是透過硬體感應器得到的數據再經由軟體運算產生數據。

運動感測器主要用來監測裝置的運動,比如傾斜、震動、旋轉、擺動。這運動我們可以看成兩類,第一類運動通常是使用者直接輸入的反射(例如使用在遊戲中操控汽車,或是使用者在遊戲中控制球),第二類是裝置在自然環境下的反射(例如裝置與你在車中一起移動)。由運動感應器通常無法用來監測裝置位置,但是可以和其他感應器一起使用,例如地磁場感應器,決定裝置的位置。


所有的運動感應器對於每一個SensorEvent都是回傳多維度的陣列數據,通常都是float型態的陣列。下表總結了在Android平台可用的運動感應器。



SensorSensor event dataDescriptionUnits of measure
TYPE_ACCELEROMETERSensorEvent.values[0]Acceleration force along the x axis (including gravity).m/s2
SensorEvent.values[1]Acceleration force along the y axis (including gravity).
SensorEvent.values[2]Acceleration force along the z axis (including gravity).
TYPE_GRAVITYSensorEvent.values[0]Force of gravity along the x axis.m/s2
SensorEvent.values[1]Force of gravity along the y axis.
SensorEvent.values[2]Force of gravity along the z axis.
TYPE_GYROSCOPESensorEvent.values[0]Rate of rotation around the x axis.rad/s
SensorEvent.values[1]Rate of rotation around the y axis.
SensorEvent.values[2]Rate of rotation around the z axis.
TYPE_LINEAR_ACCELERATIONSensorEvent.values[0]Acceleration force along the x axis (excluding gravity).m/s2
SensorEvent.values[1]Acceleration force along the y axis (excluding gravity).
SensorEvent.values[2]Acceleration force along the z axis (excluding gravity).
TYPE_ROTATION_VECTORSensorEvent.values[0]Rotation vector component along the x axis (x * sin(θ/2)).Unitless
SensorEvent.values[1]Rotation vector component along the y axis (y * sin(θ/2)).
SensorEvent.values[2]Rotation vector component along the z axis (z * sin(θ/2)).
SensorEvent.values[3]Scalar component of the rotation vector ((cos(θ/2)).1


在運動偵測和監測上,旋轉向量感應器與重力感應器是最常使用的感應器。旋轉向量感應器應用範圍很廣,比如偵測手勢、監測角度的變化、監測方向的變化。


Android Open Source Project Sensors


Android open source project(AOSP)提供三種基於軟體的感應器,重力感應器、線性加速感應器、旋轉向量感應器,這些感應器在Android 4.0中更新且現在利用裝置上的陀螺儀改善穩定性和效能,如果你想試著使用這些感應器,可以使用getVendor()和getVersion()方法便是它們。用vendor和vesion號碼辨識它們是有必要的,因為Android系統將這些感應器是為次要的感應器。例如,如果你的裝置製造商有提供它們自己的重力感應器,那麼AOSP的重力感應器就會顯示為次要的感應器。這三個感應器接依賴陀螺儀,所以如果裝置沒有陀螺儀,這些感應器就不會顯示,也不能使用。