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
So here is what I have done until now. It works, but I am not sure if it is best practice.
1) The cookie store initialises from the sharedpreference. so just create a new one each time you need it. be sure to use the same context each time. I am using getApplicationContext()
2) and 4) The cookie store handels it all for you. Just create a new one with the same context as the one you created earlier. As long as you are consistent, the cookies will initialise properly.
3) the cookie store keeps the shared preferences and its local attributes in sync so just call (new PersistentCookieStore(getApplicationContext())).clear();
My Code
RestClient.java
public static void setCookieStore(PersistentCookieStore cookieStore) {
client.setCookieStore(cookieStore);
}
LoginActivity.java
RestClient.setCookieStore(new PersistentCookieStore(getApplicationContext()));
MainActivity.java
private void loginRouter() {
PersistentCookieStore mCookieStore = new PersistentCookieStore(
getApplicationContext());
List<Cookie> cookies = mCookieStore.getCookies();
for (Cookie c : cookies) {
if (c.getName().equals("session")) {
startActivity(new Intent(this, HomeActivity.class));
finish();
}
}
launchSplashPage();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.