Search code examples
androidwear-osandroid-wear-data-api

How to call saved dataItem in Android Wear?


I'm creating a watchface that can have the color customized through an App that is on the phone.

I've seen examples use the DataApi and DataItem to save/load settings.

The problem I am encountering is that when I change to a different watchface and change back, all the values inside the DataMap seems to be reset to null or 0.

Here is a sample of my onCreate() method of the Wear watchface, which will try to load the last used color:

    PendingResult<DataItemBuffer> results = Wearable.DataApi.getDataItems(mGoogleApiClient);
    results.setResultCallback(new ResultCallback<DataItemBuffer>() {
        @Override
        public void onResult(DataItemBuffer dataItems) {
        if (dataItems.getCount() != 0) {
            for (int i = 0; i < dataItems.getCount(); i++) {
                DataMapItem dataMapItem = DataMapIfromDataItem(dataItems.get(i));
                if (dataMapItem.getDataMap().containsKey(COLOR_KEY)) {
                    mSelectedColor = dataMapItem.getDataMap().getInt(COLOR_PATH);
                    }
                }
            }
            dataItems.release();
        }
    });

Note that the mSelectedColor = dataMap... line will return 0.

Here is the code sample from the mobile app that will store this data:

        PutDataMapRequest dataMap = PutDataMapRequest.create(COLOR_PATH);
        dataMap.getDataMap().putInt(COLOR_KEY, mSelectedColor);

Sending/retreiving the color value works while running, and onDestroy() or onStop() aren't modifying the data back to 0.

Are dataItems automatically "disposed" when an activity/watchface is closed, or am I implementing this thing wrong?

Thanks for the helps!


Solution

  • I think you've got the wrong constant on your getInt call. COLOR_PATH is the URI path, COLOR_KEY is the key of the int you're trying to retrieve. You should have:

    mSelectedColor = dataMapItem.getDataMap().getInt(COLOR_KEY);