11

I want to sync preference between handhelds and wearables. I implement sample code on handheld app.

PutDataMapRequest dataMap = PutDataMapRequest.create("/count");
dataMap.getDataMap().putInt(COUNT_KEY, count++);
PutDataRequest request = dataMap.asPutDataRequest();
PendingResult<DataApi.DataItemResult> pendingResult = Wearable.DataApi
    .putDataItem(mGoogleApiClient, request);
System.out.println(dataMap.getDataMap().getInt("COUNT_KEY"));//print 3

And then implement below code on wearable app. But saved count can't be retrieved.

 PutDataMapRequest dataMap = PutDataMapRequest.create("/count");
 int count = dataMap.getDataMap().getInt("COUNT_KEY");
 System.out.println(count);//print 0

I tried in actual android handheld device and emulator of Android wear. I confirmed they are connected by using demo cards of Android Wear app.

What I need more or do I misunderstand something?

Community
  • 1
  • 1
Loran
  • 223
  • 2
  • 15

1 Answers1

19

With that code, you are trying to create a second put request, not reading the previously stored data. That's why it's empty.

The way to access previously stored data is with the DataApi methods. For example, you can get all stored data with Wearable.DataApi.getDataItems():

PendingResult<DataItemBuffer> results = Wearable.DataApi.getDataItems(mGoogleApiClient);
results.setResultCallback(new ResultCallback<DataItemBuffer>() {
    @Override
    public void onResult(DataItemBuffer dataItems) {
        if (dataItems.getCount() != 0) {
            DataMapItem dataMapItem = DataMapItem.fromDataItem(dataItems.get(0));

            // This should read the correct value.
            int value = dataMapItem.getDataMap().getInt(COUNT_KEY);
        }

        dataItems.release();
    }
});

I've used this and it works. However, I'm having a problem myself, as I don't know the Uri to access a specific data item with Wearable.DataApi.getDataItem(). So I posted this question. If you're just testing though, DataApi.getDataItems() should suffice.

Another option is to use DataApi.addListener() to be notified of changes to the storage.

Community
  • 1
  • 1
matiash
  • 54,791
  • 16
  • 125
  • 154
  • I implemented this code but onResult() doesn't run. I tried pendingResult.await(); on another thread and found this process doesn't finish. – Loran Jul 13 '14 at 07:09
  • @lamrongol Did you connect to play services before? – matiash Jul 13 '14 at 07:53
  • Sorry, I had overlooked connect() on [Accessing the Wearable Data Layer](http://developer.android.com/training/wearables/data-layer/accessing.html). Now it works, thank you. – Loran Jul 13 '14 at 09:06