当我按下按钮时,我想获得谷歌适合的总卡路里,但当我按下按钮时,应用程序关闭而不会出现错误,我无法获得卡路里。使用相同的代码,如果我将卡路里更改为步骤,它将完美无缺。这是代码:
public class MainActivity extends AppCompatActivity implements OnDataPointListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private static final int REQUEST_OAUTH = 1;
private static final String TAG = "GFIT";
private static final String AUTH_PENDING = "auth_state_pending";
private boolean authInProgress = false;
public static GoogleApiClient mApiClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null) {
authInProgress = savedInstanceState.getBoolean(AUTH_PENDING);
}
mApiClient = new GoogleApiClient.Builder(this)
.addApi(Fitness.SENSORS_API)
.addApi(Fitness.RECORDING_API)
.addApi(Fitness.HISTORY_API)
.addApi(Fitness.SESSIONS_API)
.addApi(Fitness.CONFIG_API)
.addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ))
.addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ_WRITE))
.addScope(new Scope(Scopes.FITNESS_LOCATION_READ))
.addConnectionCallbacks(this).addOnConnectionFailedListener(this)
.build();
}
@Override
protected void onStart() {
super.onStart();
mApiClient.connect();
}
@Override
public void onConnected(@Nullable Bundle bundle) {
Toast.makeText(this, "Conected", Toast.LENGTH_SHORT).show();
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
if (!authInProgress) {
try {
authInProgress = true;
connectionResult.startResolutionForResult(MainActivity.this, REQUEST_OAUTH);
} catch (IntentSender.SendIntentException e) {
Toast.makeText(getApplicationContext(), "Failed connection", Toast.LENGTH_SHORT).show();
}
} else {
Log.e("GoogleFit", "AuthInProgress");
}
Toast.makeText(getApplicationContext(), "Failed connection", Toast.LENGTH_SHORT).show();
}
@Override
public void onDataPoint(DataPoint dataPoint) {
for (final Field field : dataPoint.getDataType().getFields()) {
final Value value = dataPoint.getValue(field);
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), "Field" + field.getName() + "Value:" + value, Toast.LENGTH_SHORT).show();
}
});
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_OAUTH) {
authInProgress = false;
if (resultCode == RESULT_OK) {
if (!mApiClient.isConnecting() && !mApiClient.isConnected()) {
mApiClient.connect();
}
} else if (resultCode == RESULT_CANCELED) {
Log.e(TAG, "RESULT_CANCELED");
}
} else {
Log.e(TAG, "requestCode NOT request_oauth");
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
protected void onStop() {
super.onStop();
Fitness.SensorsApi.remove(mApiClient, this)
.setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(@NonNull Status status) {
if (status.isSuccess()) {
mApiClient.disconnect();
}
}
});
}
@Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
outState.putBoolean(AUTH_PENDING, authInProgress);
}
public void resources(View view) {
new getCal().execute();
}
private class getCal extends AsyncTask<Object, Object, Long> {
@Override
protected Long doInBackground(Object... voids) {
long total = 0;
PendingResult<DailyTotalResult> result = Fitness.HistoryApi.readDailyTotal(mApiClient, DataType. TYPE_CALORIES_EXPENDED);
DailyTotalResult totalResult = result.await(30, TimeUnit.SECONDS);
if (totalResult.getStatus().isSuccess()) {
DataSet totalSet = totalResult.getTotal();
if (totalSet != null) {
total = totalSet.isEmpty()
? 0
: totalSet.getDataPoints().get(0).getValue(Field.FIELD_CALORIES).asInt();
}
} else {
Log.w(TAG, "There was a problem getting the calories.");
}
return total;
}
@Override
protected void onPostExecute(Long aLong) {
super.onPostExecute(aLong);
//Total calories burned for that day
Toast.makeText(getApplicationContext(),"Cal:"+aLong,Toast.LENGTH_SHORT).show();
}
}
消息错误:
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.example.smoreno.gfitprueba, PID: 28554
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:321)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:246)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:833)
Caused by: java.lang.IllegalStateException: Value is not in int format
at com.google.android.gms.common.internal.zzac.zza(Unknown Source)
at com.google.android.gms.fitness.data.Value.asInt(Unknown Source)
at com.example.smoreno.gfitprueba.MainActivity$getpasoshoy.doInBackground(MainActivity.java:422)
at com.example.smoreno.gfitprueba.MainActivity$getpasoshoy.doInBackground(MainActivity.java:410)
at android.os.AsyncTask$2.call(AsyncTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:246)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:833)
感谢您的帮助。
答案 0 :(得分:0)
问题在于totalSet.getDataPoints().get(0).getValue(Field.FIELD_CALORIES)asInt();
虽然这会返回float
,但您将其分配给long
。
FIX:
private class getCal extends AsyncTask<Object, Object, Long> {
@Override
protected Long doInBackground(Object... voids) {
float total = 0.0;
PendingResult<DailyTotalResult> result = Fitness.HistoryApi.readDailyTotal(mApiClient, DataType. TYPE_CALORIES_EXPENDED);
DailyTotalResult totalResult = result.await(30, TimeUnit.SECONDS);
if (totalResult.getStatus().isSuccess()) {
DataSet totalSet = totalResult.getTotal();
if (totalSet != null) {
total = totalSet.isEmpty()
? 0
: totalSet.getDataPoints().get(0).getValue(Field.FIELD_CALORIES).asInt();
}
} else {
Log.w(TAG, "There was a problem getting the calories.");
}
return total;
}
@Override
protected void onPostExecute(Long aLong) {
super.onPostExecute(aLong);
//Total calories burned for that day
Toast.makeText(getApplicationContext(),"Cal:"+aLong,Toast.LENGTH_SHORT).show();
}
}