Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/api/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 通过google fit快速获取卡路里_Android_Api_Google Fit - Fatal编程技术网

Android 通过google fit快速获取卡路里

Android 通过google fit快速获取卡路里,android,api,google-fit,Android,Api,Google Fit,当我按下按钮时,我想在我的google fit上获取总热量,但当我按下按钮时,应用程序关闭而不留下错误,我无法获取热量。使用相同的代码,如果我将卡路里改为步数,效果会非常好。代码如下: public class MainActivity extends AppCompatActivity implements OnDataPointListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedLi

当我按下按钮时,我想在我的google fit上获取总热量,但当我按下按钮时,应用程序关闭而不留下错误,我无法获取热量。使用相同的代码,如果我将卡路里改为步数,效果会非常好。代码如下:

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();

    }
}
感谢您的帮助。

问题在于totalSet.getDataPoints.get0.getValueField.FIELD\u卡路里‌​‌​萨辛特

当它返回一个浮点值时,您将其分配给long

修复方法:


发布日志抱歉,我现在还没有完成MainActivity.java行:422中的代码有什么作用?你能告诉我那行代码是什么吗?我代码中的第422行是:total=totalSet.isEmpty?0:totalSet.getDataPoints.get0.getValueField.FIELD_.asInt;您可以将total定义为double并调用totalSet.getDataPoints.get0.getValueField.FIELD\u卡路里,而不是将total设置为long吗‌​有什么?
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) 
    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();

    }
}