Chris D Chris D - 19 days ago 6
Android Question

Creating Custom DataType for GoogleFit

I've been trying to create a custom data type for a google fit application and I have been running into a few errors. Originally ConfigApi.createCustomDataType was getting the following error

"non-static method 'createCustomDataType (com.google.android.gms.common.api.GoolgeApiClient, com.google.android.gms.fitness.request.DataTypeCreateRequest)cannot be referenced from a static context"

So I instantiated the ConfigApi to bypass that error and then I got the following error when I ran the application:

java.lang.NullPointerException: Attempt to invoke interface method 'void com.google.android.gms.common.api.PendingResult.setResultCallback(com.google.android.gms.common.api.ResultCallback)' on a null object reference

That error is coming on this line: pendingResult.setResultCallback

I'm hoping someone can help me out with what I doing wrong before I start to make a bigger mess than I already have. Below is the code I am working with:

// build a request to create a new data type
DataTypeCreateRequest request = new DataTypeCreateRequest.Builder()
.setName(myPackageName)
.addField("custom", Field.FORMAT_INT32)
.build();

// invoke the CONFIG API with (Google API client object and create data type request)

// instantiating ConfigApi due to the following error:
// non-static method createCustomDataType cannot be referenced from a static context

ConfigApi configApi = new ConfigApi() {
@Override
public PendingResult<DataTypeResult> createCustomDataType(GoogleApiClient googleApiClient, DataTypeCreateRequest dataTypeCreateRequest) {
return null;
}

@Override
public PendingResult<DataTypeResult> readDataType(GoogleApiClient googleApiClient, String s) {
return null;
}

@Override
public PendingResult<Status> disableFit(GoogleApiClient googleApiClient) {
return null;
}
};

PendingResult<DataTypeResult> pendingResult =
configApi.createCustomDataType(mClient, request);
/**
* ConfigApi.createCustomDataType was getting the following error:
* non-static method 'createCustomDataType
* (com.google.android.gms.common.api.GoolgeApiClient,
* com.google.android.gms.fitness.request.DataTypeCreateRequest)
* cannot be referenced from a static context
*/

// 3. Check the result asynchronously
// (The result may not be immediately available)
pendingResult.setResultCallback(
new ResultCallback<DataTypeResult>() {
@Override
public void onResult(DataTypeResult dataTypeResult) {

if (dataTypeResult.getStatus().isSuccess()){
DataType customType = dataTypeResult.getDataType();
// Use this custon data type to insert data in your app
onDataTypeAvailable(customType);
}

// Retrieve the created data type
// Use this custom data type to insert data in your app
// (see other examples)

}
}
);
}

Answer

When you create your GoogleApiClient, make sure to add the config API:

 GoogleApiClient client = new GoogleApiClient.Builder()
     .addApi(Fitness.CONFIG_API)
     ...
     .build();