Get Lifelog API result

152 Views Asked by At

I'm trying to use the Lifelog's API and i wrote this portion of code:

.
.
.
//MAIN ACTIVITY
private void scaricaDati(){

    token = spref.getString("access_token");

    Log.i(TAG, "(scaricaDati) token = " + token);

    String tag_json_obj = "json_obj_req";

    String url = "https://platform.lifelog.sonymobile.com/v1/users/me/activities";
    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
            url, null,
            new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    Log.i("MainActivity response ", response.toString());

                    try {
                        Log.i(TAG,"Ottieni Dati");
                        JSONArray result=response.getJSONArray("result");
                        Log.i("MainActivity result",result.toString());
                        for (int i = 0; i < result.length(); i++) {
                            JSONObject jsonobject = result.getJSONObject(i);


                            String startTime = jsonobject.getString("startTime");
                            Log.i("MainActivity start time",startTime.toString());
                            String endTime = jsonobject.getString("endTime");
                            Log.i("MainActivity end time",endTime.toString());


                        }



                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d("MainActivity ", "Error: " + error.getMessage());

        }
    }) {

        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("start_time", "2016-04-07T17:00:00.000Z");
            params.put("end_time", "2016-04-07T18:00:00.000Z");
            params.put("type", "physical:walk");
            return params;
        }


        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Authorization", "Bearer "+ token);
            headers.put("Accept", "application/json");
            //headers.put("Accept-Encoding", "gzip");
            //headers.put("Content-Encoding", "gzip");
            return headers;
        }
    };

    // Adding request to request queue
    ApplicationController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
}
.
.
.

//LIFELOG CLASS WITH THE "DOLOGIN" METHOD


public static final int LOGINACTIVITY_REQUEST_CODE = 2231;

public static final String API_BASE_URL = "https://platform.lifelog.sonymobile.com";

public static final String LIFELOG_PREFS = "lifelog_prefs";
static String client_id = "";
static String client_secret = "";
static String login_scope = "";
static String callback_url = "";
static String auth_token = "";

public static String getClient_id() {
    return client_id;
}

public static String getClient_secret() {
    return client_secret;
}

public static String getCallback_url() {
    return callback_url;
}

public static String getAuth_token() {
    return auth_token;
}

public static void initialise(String id, String secret, String callbackUrl) {
    client_id = id;
    client_secret = secret;
    callback_url = callbackUrl;
    setScope(Scopes.PROFILE_READ, Scopes.ACTIVITIES_READ, Scopes.LOCATIONS_READ);
}

public static String getScope() {
    return login_scope;
}

public static void setScope(String... scopes) {
    login_scope = "";
    for (String scope : scopes) {
        if (TextUtils.isEmpty(login_scope)) {
            login_scope = scope;
        } else {
            login_scope += "+" + scope;
        }
    }
}


public static void doLogin(Activity activity) {
    Intent loginIntent = new Intent(activity, LoginActivity.class);
    activity.startActivityForResult(loginIntent, LOGINACTIVITY_REQUEST_CODE);
}

public static void checkAuthentication (Context context, final OnAuthenticationChecked oac) {
    SecurePreferences securePreferences = new SecurePreferences(
            context,
            LIFELOG_PREFS,
            getClient_secret(),
            true
    );
    if (securePreferences.containsKey(GetAuthTokenTask.AUTH_ACCESS_TOKEN)) {
        auth_token = securePreferences.getString(GetAuthTokenTask.AUTH_ACCESS_TOKEN);
        long expires_in = Long.valueOf(securePreferences.getString(GetAuthTokenTask.AUTH_EXPIRES_IN));
        if (expires_in > 120) {
            oac.onAuthChecked(true);
        } else {
            RefreshAuthTokenTask ratt = new RefreshAuthTokenTask(context);
            ratt.refreshAuth(new RefreshAuthTokenTask.OnAuthenticatedListener() {
                @Override
                public void onAuthenticated(String token) {
                    auth_token = token;
                    oac.onAuthChecked(true);
                }
            });
        }
    }
    oac.onAuthChecked(false);
}

public interface OnAuthenticationChecked {
    void onAuthChecked(boolean authenticated);
}

public static class Scopes {
    public static final String PROFILE_READ = "lifelog.profile.read";
    public static final String ACTIVITIES_READ = "lifelog.activities.read";
    public static final String LOCATIONS_READ = "lifelog.locations.read";
}

.
.
.
//GetAuthTokenTask class

private static final String TAG = "LifeLog:GetAuthToken";
private static final String OAUTH2_URL = "https://platform.lifelog.sonymobile.com/oauth/2/token";
public static final String AUTH_ACCESS_TOKEN = "access_token";
public static final String AUTH_EXPIRES_IN = "expires_in";
public static final String AUTH_REFRESH_TOKEN = "refresh_token";
public static final String AUTH_TOKEN_TYPE = "token_type";
public static final String AUTH_REFRESH_TOKEN_EXPIRES_IN = "refresh_token_expires_in";
private final static String PARAM_CLIENT_ID = "client_id";
private final static String PARAM_CLIENT_SECRET = "client_secret";
private final static String PARAM_GRANT_TYPE = "grant_type";
private final static String PARAM_CODE = "code";
private final Context mContext;
private OnAuthenticatedListener onAuthenticatedListener;
public GetAuthTokenTask(Context context) {
    this.mContext = context;
}

public void getAuth(final String authCode, OnAuthenticatedListener oal) {
    onAuthenticatedListener = oal;

    final String authRequestBody =
            PARAM_CLIENT_ID + "=" + LifeLog.getClient_id() + "&"
                    + PARAM_CLIENT_SECRET + "=" + LifeLog.getClient_secret() + "&"
                    + PARAM_GRANT_TYPE + "=" + "authorization_code" + "&"
                    + PARAM_CODE + "=" + authCode;

    JsonObjectRequest authRequest = new JsonObjectRequest(Request.Method.POST,
            OAUTH2_URL,
            (JSONObject)null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject jObj) {
                    try {

                        SecurePreferences spref = new SecurePreferences(mContext,
                                LifeLog.LIFELOG_PREFS, LifeLog.getClient_secret(), true);
                        spref.put(AUTH_ACCESS_TOKEN, jObj.getString(AUTH_ACCESS_TOKEN));
                        spref.put(AUTH_EXPIRES_IN, jObj.getString(AUTH_EXPIRES_IN));
                        spref.put(AUTH_TOKEN_TYPE, jObj.getString(AUTH_TOKEN_TYPE));
                        spref.put(AUTH_REFRESH_TOKEN, jObj.getString(AUTH_REFRESH_TOKEN));
                        spref.put(AUTH_REFRESH_TOKEN_EXPIRES_IN,
                                  jObj.getString(AUTH_REFRESH_TOKEN_EXPIRES_IN));
                        if (Debug.isDebuggable(mContext)) {
                            Log.d("TOKEN", jObj.getString(AUTH_ACCESS_TOKEN));
                            Log.d("REFRESH TOKEN", jObj.getString(AUTH_REFRESH_TOKEN));

                        }
                        if (onAuthenticatedListener != null) {
                            onAuthenticatedListener.onAuthenticated(jObj.getString(AUTH_ACCESS_TOKEN));
                        }
                    } catch (JSONException e) {
                        if (onAuthenticatedListener != null) {
                            onAuthenticatedListener.onError(e);
                        }
                    }

                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    if (onAuthenticatedListener != null) {
                        onAuthenticatedListener.onError(volleyError);
                    }
                }
            }
    ) {
        @Override
        public String getBodyContentType() {
            return String.format("application/x-www-form-urlencoded; charset=%s", new Object[]{"utf-8"});
        }

        @Override
        public byte[] getBody() {
            return authRequestBody.getBytes(Charset.forName("utf-8"));
        }

    };
    VolleySingleton.getInstance(mContext).addToRequestQueue(authRequest);
}

public interface OnAuthenticatedListener {
    void onAuthenticated(String authToken);
    void onError(Exception e);
}

.
.
.

//RefreshAuthTokenTask class

    public static final String TAG = "LifeLog:RefreshAuth";
public static final String OAUTH2_URL = "https://platform.lifelog.sonymobile.com/oauth/2/refresh_token";
public static final String AUTH_ACCESS_TOKEN = "access_token";
public static final String AUTH_ISSUED_AT = "issued_at";
public static final String AUTH_EXPIRES_IN = "expires_in";
public static final String AUTH_EXPIRES = "expires";
public static final String AUTH_REFRESH_TOKEN = "refresh_token";
static String PARAM_CLIENT_ID = "client_id";
static String PARAM_CLIENT_SECRET = "client_secret";
static String PARAM_GRANT_TYPE = "grant_type";
static String PARAM_REFRESH_TOKEN = "refresh_token";
private Context mContext;
private OnAuthenticatedListener onAuthenticatedListener;
public RefreshAuthTokenTask(Context context) {
    this.mContext = context;
}

public void refreshAuth(OnAuthenticatedListener oal) {
    onAuthenticatedListener = oal;
    final SecurePreferences spref = new SecurePreferences(mContext,
            LifeLog.LIFELOG_PREFS, LifeLog.getClient_secret(), true);

    final String refreshAuthBody =
            PARAM_CLIENT_ID + "=" + LifeLog.getClient_id() + "&"
                    + PARAM_CLIENT_SECRET + "=" + LifeLog.getClient_secret() + "&"
                    + PARAM_GRANT_TYPE + "=" + "refresh_token" + "&"
                    + PARAM_REFRESH_TOKEN + "=" + spref.getString(AUTH_REFRESH_TOKEN);

    Log.d(TAG, refreshAuthBody);

    JsonObjectRequest authRequest = new JsonObjectRequest(Request.Method.POST,
            OAUTH2_URL,
            null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject jObj) {
                    try {

                        spref.put(AUTH_ACCESS_TOKEN, jObj.getString(AUTH_ACCESS_TOKEN));
                        spref.put(AUTH_EXPIRES_IN, jObj.getString(AUTH_EXPIRES_IN));
                        spref.put(AUTH_EXPIRES, jObj.getString(AUTH_EXPIRES));
                        spref.put(AUTH_ISSUED_AT, jObj.getString(AUTH_ISSUED_AT));
                        spref.put(AUTH_REFRESH_TOKEN, jObj.getString(AUTH_REFRESH_TOKEN));
                        Log.d("NEW TOKEN", jObj.getString(AUTH_ACCESS_TOKEN));
                        Log.d("NEW EXPIRATION", jObj.getString(AUTH_EXPIRES));
                        Log.d("NEW REFRESH TOKEN", jObj.getString(AUTH_REFRESH_TOKEN));
                        if (onAuthenticatedListener != null) {
                            onAuthenticatedListener.onAuthenticated(jObj.getString(AUTH_ACCESS_TOKEN));
                        }
                    } catch (JSONException e) {
                        //TODO: handle malformed json
                    }

                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {

                }
            }
    ) {
        @Override
        public String getBodyContentType() {
            return String.format("application/x-www-form-urlencoded; charset=%s", new Object[]{"utf-8"});
        }

        @Override
        public byte[] getBody() {
            return refreshAuthBody.getBytes(Charset.forName("utf-8"));
        }

    };
    VolleySingleton.getInstance(mContext).addToRequestQueue(authRequest);
}

public interface OnAuthenticatedListener {
    void onAuthenticated(String auth_token);
}

in the onResponse i receive a lot of data, also for days and hours different from the day and the interval of time setted in the getParams, why? where is the error? If i remove the getParams method i obtain the same data as results.

1

There are 1 best solutions below

0
On

I believe the answer may be that you are using JSONObjectRequest instead of StringRequest. JsonObjectRequest overrides the getBody() method so your getParam() method never runs. You can read more about this here.

Android: Volley HTTP Request custom header

Trying using StringRequest to see if that works.