I am new to Android Development. Had a few questions on what is the best way to make the libraries mentioned above work optimally.
Currently, I have three activities in my app. MainActivity, LoginActivity and HomeActivity. The app launches the MainActivity which is supposed to check if the person is logged in. If the person is logged in, redirect to Home, else redirect to Login.
As mentioned in the documentation, I created a RestClient class. I can successfully make a request in my LoginActivity and get a response. This is my code for the login.
public void login() {
RequestParams params = new RequestParams();
params.put(AUTH_PARAMETER_EMAIL, mEmail);
params.put(AUTH_PARAMETER_PASSWORD, mPassword);
RestClient.setCookieStore(new PersistentCookieStore(this));
RestClient.post(AUTH_URL, params, new JsonHttpResponseHandler() {
@Override
public void onFinish() {
showProgress(false);
}
@Override
public void onSuccess(JSONObject response) {
String response_status = null;
try {
response_status = response.getString(AUTH_RESPONSE_STATUS);
} catch (JSONException e) {
Toast.makeText(LoginActivity.this,
"ERROR: " + e.toString(), Toast.LENGTH_LONG).show();
Log.e(TAG, e.toString());
}
if (response_status.equals(AUTH_SUCCESS_STATUS)) {
finish();
} else {
mPasswordView
.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
@Override
public void onFailure(Throwable e, String content) {
Toast.makeText(LoginActivity.this, "ERROR: " + e.toString(),
Toast.LENGTH_LONG).show();
Log.e(TAG, e.toString());
}
});
}
Questions
- This is going to create a new cookie store each time a request is made. Where should i put it so that it is only created once? Should i put it in the onCreate of the MainActivity and then assign it to a global variable? Is that the best practice?
- In my MainActivity, how can I check for the session cookie that was sent from the server? I know it is in shared preferences, but how can i get it? The documentation doesnt say what variable it will be stored under in the SharedPreferences.
- When I need to logout someone, do I delete the shared preferences or erase the cookie store or both? Are they automatically kept in sync?
- When the app restarts, how do i initialise the cookie store from the saved data in the sharedpreferences?
- If you know of any open-sourced code that properly implements this, Ill be happy to look at it and answer these questions myself. Just provide a link!