2017-01-18 7 views
0

Ich möchte die Gesamtkalorien auf meinem Google fit whe ich einen Knopf drücken, aber wenn ich den Knopf drücken, schließt die App ohne einen Fehler zu verlassen, und ich kann die Kalorien nicht erhalten. Mit dem gleichen Code, wenn ich die Kalorien in Schritte ändere, funktioniert es perfekt. Hier ist der Code:Absturz bekommen Kalorien 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(); 

    } 
} 

die Fehlermeldung:

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)  

Vielen Dank für Ihre Hilfe.

+0

post die logcat – OBX

+0

sorry, i'ts jetzt getan – zasaz

+0

Was bedeutet der Code in MainActivity.java Zeile: 422 tun? Können Sie sagen, welcher Code in dieser Zeile steht? – OBX

Antwort

0

Das Problem ist mit totalSet.getDataPoints().get(0).getValue(Field.FIELD_CALORIE‌​‌​S)asInt();

während dies eine float gibt, können Sie es zu long zuweisen.

Der UPDATE:

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

    } 
} 
Verwandte Themen