How to get Total Sleep from Google Fit REST API - java

I tried this using java
String AccessToken = "TOKEN";
String ApiUrl = "https://www.googleapis.com/fitness/v1/users/me/sessions?startTime=2017-02-28T22:00:00.00Z&endTime=2017-03-01T10:59:59.99Z";
HttpClient httpclient = HttpClientBuilder.create().build();
try {
HttpGet httpPost = new HttpGet(ApiUrl);
httpPost.addHeader("Authorization", "Bearer " + AccessToken);
HttpResponse response = httpclient.execute(httpPost);
`enter code here` System.out.println("\nSending 'GET' request to URL : " + ApiUrl);
HttpEntity entity = response.getEntity();
BufferedReader rd = new BufferedReader(
new InputStreamReader(entity.getContent()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println("line" + line);
}
} catch (Exception e) {
System.out.println("Exception at getDataFromUrl ,error is " + e.getMessage());
}
And I am getting response like
{
"session": [
{
"id": "Deep sleep141488319560000",
"name": "Deep sleep14",
"startTimeMillis": "1488319560000",
"endTimeMillis": "1488320700000",
"modifiedTimeMillis": "1488374094270",
"application": {
"packageName": "com.xiaomi.hm.health"
},
"activityType": 72
},
{
"id": "Deep sleep161488321420000",
"name": "Deep sleep16",
"startTimeMillis": "1488321420000",
"endTimeMillis": "1488322500000",
"modifiedTimeMillis": "1488374094280",
"application": {
"packageName": "com.xiaomi.hm.health"
},
"activityType": 72
},
{
"id": "Deep sleep201488328680000",
"name": "Deep sleep20",
"startTimeMillis": "1488328680000",
"endTimeMillis": "1488330360000",
"modifiedTimeMillis": "1488374094303",
"application": {
"packageName": "com.xiaomi.hm.health"
},
"activityType": 72
},
{
"id": "Light sleep131488318900000",
"name": "Light sleep13",
"startTimeMillis": "1488318900000",
"endTimeMillis": "1488319560000",
"modifiedTimeMillis": "1488374094265",
"application": {
"packageName": "com.xiaomi.hm.health"
},
"activityType": 72
}]}
But i want get total sleep e.g 7 hours 10 mins
Is it correct API I am using or am i missing something.
Any help appreciated. I am new to Google Fit.
Note:This is java not Android.

You must calculate the sleep duration on your own by computing the difference between "endTimeMillis" and "startTimeMillis" and summerize these computed values in your requested range. That’s easy, but also tricky as the stored data may differ from the source (the app that sends the data to google fit).
I also run in this issue and did not find a satisfying solution yet that is working correct. Since sleep data it is not a "real" data type (see https://developers.google.com/fit/rest/v1/data-types#public_data_types) you cannot be sure that an app sends duplicate values within the same requested range. In my case the app "xiaomi mi-fit" sends duplicate values with the same "startTimeMillis" and "endTimeMillis" so you must check this in your code. Otherwise you will be getting a sleep duration that is not accurate.
As long as Google did not support sleep data as an official data type you cannot be sure that the data is correct. Moreover: When different apps send their sleep data to the same google fit account the data will not be aggregated, you will have to sort this on your own by filtering the package name (app) that sends the data.
Also, Google removed the visibility of sleep data in their own native app (version 2.x) and in their WebView (https://fit.google.com) too!

Related

Get all records from JSON response

I'm still kind of new to the Rest Assured API world. I've read through as much documentation on https://github.com/rest-assured/rest-assured/wiki/Usage#example-3---complex-parsing-and-validation as I can stand.
I have a response that looks like:
{
"StatusCode": 200,
"Result": [
{
"EmployeeId": "5661631",
"PhoneTypeDescription": "Home",
"PhoneNumber": "9701234567",
},
{
"EmployeeId": "5661631",
"PhoneTypeDescription": "mobile1",
"PhoneNumber": "2531234567",
},
{
"EmployeeId": "5661631",
"PhoneTypeDescription": "mobile2",
"PhoneNumber": "8081234567",
}
]
}
I've been struggling with how to get just the first record's PhoneNumber.
String responseBody=
given()
.relaxedHTTPSValidation().contentType("application/json")
.param("api_key", api_key).
when()
.get("/api/employees/" + employeeId)
.andReturn().asString();
JsonPath jsonPath = new JsonPath(responseBody).setRoot("Result");
phoneNumber = jsonPath.getString("PhoneNumber");
I get all the phone numbers in this case:
phoneNumber = "[9701234567,2531234567,8081234567]"
How can I get just the first record? I'd rather not have to perform string operations to deal with the, "[".
Thanks
You can simply do,
JSONObject json = new JSONObject(responseBody);
phoneNumber = json.getJSONArray("Result").getJSONObject(0).getString("PhoneNumber");
Here, 0 indicates the first record in the JSON Array Result.
Because you know the index of the element you want to retrieve, you can use the following code:
JsonPath jsonPath = new JsonPath(response);
String phoneNumber = jsonPath.getString("Result[0].PhoneNumber");

Extracting text from Http response

following is the screenshot of http respone in java -
and following is the text form of response:
{
"LightGingerTheTextResult": [
{
"Confidence": 4,
"From": 0,
"LrnFrg": null,
"LrnFrgOrigIndxs": [],
"Mistakes": [
{
"CanAddToDict": false,
"From": 0,
"To": 0
}
],
"ShouldReplace": true,
"Suggestions": [
{
"LrnCatId": 12,
"Text": "An"
},
{
"LrnCatId": 45,
"Text": "A"
}
],
"To": 0,
"TopLrnCatId": 12,
"Type": 3,
"UXFrgFrom": 0,
"UXFrgTo": 6
}
]
}
I want to extract the "text" in the suggestion.
This is my part with json. I am getting final response in "finalResult"-
JSONObject json = new JSONObject();
try
{
StringBuffer response =urllib.urlopen(url);
String finalResponse= response.toString();
System.out.println("final response"+finalResponse);
StringBuffer result=(StringBuffer) json.get(finalResponse);
//finalResult=URLEncoder.encode(result.toString(), "UTF-8");
String finalResult=result.toString();
}
catch (Exception e) {
System.out.println(e.getMessage());
}
See stackoverflow.com/questions/2591098. You needs a library,
using package org.json with
new JSONObject(textOfResponse)
.getJSONArray("LightGingerTheTextResult").getJSONObject(0)
.getJSONArray("Suggestions").getJSONObject(0)
.getString("Text")
and your textOfResponse I get
An
If you are looking for a value of a specific JSON node you can use a JsonPath expression e.g. to extract values of all Text nodes:
$.LightGingerTheTextResult[*].Suggestions[*].Text
in your example simplifies to
$..Text
or just the first Text node from the first Suggestions node:
$.LightGingerTheTextResult[0].Suggestions[0].Text
I would suggest you to first start by retreive the body of your httpResponse object.
String tmp = response.body(); // I assume the callback method has a an
//argument of type
//httpResponse called response
Then store it somewhere eg:string.
Use gson and use the httpResponse class
like this:
httpResponse rep = gson.fromJson(, httpResponse .class);
This way you can now use the rep object to retreive what ever you want.

Receive JSON data from a webservice using REST API

I need to receive JSON data from this Api http://countryapi.gear.host/v1/Country/getCountries using REST API. I need to receive NativeName and Region for the specific country.
My main problem is how to send request for the specific country (for example I print Name Australia) and get the response for NativeName and Region - Australia, Oceania (it should be String).
I have such classes:
public class Client {
public static void main(String[] args) throws ClientProtocolException, IOException {
HttpClient clientGetEntity = new DefaultHttpClient();
HttpGet request = new HttpGet("http://countryapi.gear.host/v1/Country/getCountries?pName=Australia");
request.addHeader("accept", "application/json");
HttpResponse responseGetEntity = clientGetEntity.execute(request);
//String json =EntityUtils.toString((HttpEntity) responseGetEntity);
System.out.println("Request : " + request.toString());
System.out.println("Response : " + responseGetEntity.toString());
}
}
EDITS
As regards getting the specific country's name, you need to make a get request with the country name such as:
http://countryapi.gear.host/v1/Country/getCountries?pName=Australia
The response from this request:
{
"IsSuccess": true,
"UserMessage": null,
"TechnicalMessage": null,
"TotalCount": 1,
"Response": [
{
"Name": "Australia",
"Alpha2Code": "AU",
"Alpha3Code": "AUS",
"NativeName": "Australia",
"Region": "Oceania",
"SubRegion": "Australia and New Zealand",
"Latitude": "-27",
"Longitude": "133",
"Area": 7692024,
"NumericCode": 36,
"NativeLanguage": "eng",
"CurrencyCode": "AUD",
"CurrencyName": "Australian dollar",
"CurrencySymbol": "$",
"Flag": "https://api.backendless.com/2F26DFBF-433C-51CC-FF56-830CEA93BF00/473FB5A9-D20E-8D3E-FF01-E93D9D780A00/files/CountryFlags/aus.svg",
"FlagPng": "https://api.backendless.com/2F26DFBF-433C-51CC-FF56-830CEA93BF00/473FB5A9-D20E-8D3E-FF01-E93D9D780A00/files/CountryFlagsPng/aus.png"
}
]
}
You can access NativeName and region by:
data.Response[0].NativeName and data.Response[0].Region respectively.
Since the data returned from the API is always a JSON string, dont forget to parse the string before use.
----------------------------------------
I am not a java developer but I have dealt with a lot of JSON data, Also C# and TypeScript projects.
First, you should take a look at this line:
request.addHeader("accept", "application/fson");
Am afraid this is not a valid JSON request header and if we where to start debugging your code, it would be difficult to pinpoint where the problem lies if the basis of the whole request is faulty. Please correct to:
request.addHeader("accept", "application/json"); and try again, if you have the same result, we can continue debugging from there.

detect changes in google drive list returning 0 but for same pagetoken returns change list with api

Creating Java app that will capture Google Drive changes and using the Java client for the Google Drive V3 API. The code below shows how we are calling the Changes.List method to return a list of drive changes.
https://developers.google.com/drive/v3/reference/changes/list following this for page token 3411 gives list
{
"kind": "drive#changeList",
"newStartPageToken": "3420",
"changes": [
{
"kind": "drive#change",
"type": "file",
"time": "2017-06-11T10:23:44.740Z",
"removed": false,
"fileId": "0B5nxCVMvw6oHaGNXZnlIb1I1OEE",
"file": {
"kind": "drive#file",
"id": "0B5nxCVMvw6oHaGNXZnlIb1I1OEE",
"name": "NewsLetters",
"mimeType": "application/vnd.google-apps.folder"
}
},
{
"kind": "drive#change",
"type": "file",
"time": "2017-06-11T10:23:49.982Z",
"removed": false,
"fileId": "0B5nxCVMvw6oHeWdTYzlsOWpFOEU",
"file": {
"kind": "drive#file",
"id": "0B5nxCVMvw6oHeWdTYzlsOWpFOEU",
"name": "Copy of Copy of learning11.txt",
"mimeType": "text/plain"
}
},
But by using code
AppIdentityCredential credential= new
AppIdentityCredential(Collections.singleton(DriveScopes.DRIVE_METADATA));
driveService = new Drive.Builder(
HTTP_TRANSPORT_REQUEST, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME)
.build();
String pageToken = "3411";
while (pageToken != null) {
ChangeList changes = driveService.changes().list(pageToken)
.execute();
Log.info("changes.getChanges 3411 "+changes.getChanges().size());
for (Change change : changes.getChanges()) {
// Process change
System.out.println("Change found for file: " + change.getFileId());
}
if (changes.getNewStartPageToken() != null) {
// Last page, save this token for the next polling interval
savedStartPageToken = changes.getNewStartPageToken();
}
pageToken = changes.getNextPageToken();
}
It gives
Log.info("changes.getChanges 3411 "+changes.getChanges().size());
size returns 0
even I tried with
driveService.changes().list("3411"). setFields("changes").execute()
same result 0
I am using AppEngine Google cloud server.
I would like to get a list of changes in folderID.
What mistake I am doing.Any pointers. Please help.
Is this because
Google Drive API through Google App Engine
Service Accounts are not supported by the Drive SDK due to its security model.
App Identity isn't working with the Drive API. Wouldn't it be a bug
But with AppIdentity I am able to read files in folder
result = service.files().list().setQ("'" + locdriveFolderID + "' in
parents")
.setPageSize(10)
.setFields("nextPageToken, files(id,
name,description,mimeType,modifiedTime)")
.setOrderBy("modifiedTime")
.execute();
why changes.getChanges() returns 0 it should return list of changes which shows by api >1.
Please let me correct.
the result of changes.getChanges() return list if
AuthorizationCodeFlow authFlow = initializeFlow();
Credential credential = authFlow.loadCredential(getUserId(req));
driveService = new Drive.Builder(
HTTP_TRANSPORT_REQUEST, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME)
.build();
ChangeList changes = mService.changes().list("3411").execute();
Log.info("changes.getChanges "+changes.getChanges().size() );
Log output
changes.getChanges 10

Why do I always get JSON Exception?

This Is my first time with parsing JSON data. I am using the Google knowledge graph api. I got the api working and I can get the JSON result. This is Google 's sample return data for a sample query which I'm using now for testing.
{
"#context": {
"#vocab": "http://schema.org/",
"goog": "http://schema.googleapis.com/",
"resultScore": "goog:resultScore",
"detailedDescription": "goog:detailedDescription",
"EntitySearchResult": "goog:EntitySearchResult",
"kg": "http://g.co/kg"
},
"#type": "ItemList",
"itemListElement": [
{
"#type": "EntitySearchResult",
"result": {
"#id": "kg:/m/0dl567",
"name": "Taylor Swift",
"#type": [
"Thing",
"Person"
],
"description": "Singer-songwriter",
"image": {
"contentUrl": "https://t1.gstatic.com/images?q=tbn:ANd9GcQmVDAhjhWnN2OWys2ZMO3PGAhupp5tN2LwF_BJmiHgi19hf8Ku",
"url": "https://en.wikipedia.org/wiki/Taylor_Swift",
"license": "http://creativecommons.org/licenses/by-sa/2.0"
},
"detailedDescription": {
"articleBody": "Taylor Alison Swift is an American singer-songwriter and actress. Raised in Wyomissing, Pennsylvania, she moved to Nashville, Tennessee, at the age of 14 to pursue a career in country music. ",
"url": "http://en.wikipedia.org/wiki/Taylor_Swift",
"license": "https://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License"
},
"url": "http://taylorswift.com/"
},
"resultScore": 896.576599
}
]
}
So I want to parse it so that I can get the name, description, detailed description. This is my code but I always seem to get the exception. Any ideas why?
try {
JSONObject object=new JSONObject(gggg);
JSONArray itemListElement = object.getJSONArray("itemListElement");
for(int i=0; i < itemListElement.length();i++){
JSONObject c = itemListElement.getJSONObject(i);
JSONObject results = c.getJSONObject("result");
String name = results.getString("name").toString();
String description = results.getString("description").toString();
String detailedDescription = results.getString("articleBody").toString();
gggg = "Name: "+name+"\n Description: "+description+"\n "+detailedDescription;
}
responseView.append(gggg);
} catch (JSONException e) {
Toast.makeText(MainActivity.this,gggg,Toast.LENGTH_LONG).show();
}
Also the string gggg contains the JSON data. I don't know why but I am always getting the exception. Please tell me what is the error in my code and how to repair it.
Thanks.
"Name: Taylor Swift Description: Singer-songwriter Taylor Alison
Swift is an American singer-songwriter and actress. Raised in
Wyomissing, Pennsylvania, she moved to Nashville, Tennessee, at the
age of 14 to pursue a career in country music. "
The problem is your String detailedDescription line.
You need to get the detailedDescription object before you retrieve the articleBody.
for(int i=0; i < itemListElement.length();i++){
JSONObject c = itemListElement.getJSONObject(i);
JSONObject results = c.getJSONObject("result");
String name = results.getString("name");
String description = results.getString("description");
JSONObject detailedDescription = results.getJSONObject("detailedDescription");
String articleBody = detailedDescription.getString("articleBody");
String x = "Name: "+name+"\n Description: "+description+"\n "+articleBody;
}
Also your .toString() method calls are redundant as you are calling .getString() on the JSON object.
With in the android json library it has a method called has element, which returns true or false. After successfully checking then access the element. The expection be caused by tring to access an element that isn't there.
Might be worth printing out after each time you create a new object to ensure that the objects are being created. It will also piont to where the expection is happening.

Categories