Skip to content

Instantly share code, notes, and snippets.

@ishmaelmakitla
Last active October 22, 2016 08:33
Show Gist options
  • Save ishmaelmakitla/28f9e162d79726aac20f7db1d59caeec to your computer and use it in GitHub Desktop.
Save ishmaelmakitla/28f9e162d79726aac20f7db1d59caeec to your computer and use it in GitHub Desktop.
package za.co.ishlema.blog.examples;
/**
* This is an example of implementing "remember me" login option using SharedPreferences in Android.
* @author Ishmael Makitla,
*
* */
public class LoginActivity extends Activity {
private static final String TAG = LoginActivity.class.getSimpleName();
public static final String USER_SHAREDPREFERENCE_KEY = "userPrefKey";
public static final String USER_SHAREDPREFERENCE_VALIDITY_KEY = "valid";
//BY DEFAULT the app should remember the user (auto-login) for at most 5 days - unless if he logs out explicitly.
public static final long DEFAULT_REMEMBER_UNTIL = (1000*60*60*24*5);
//shared preferences
SharedPreferences sharedPreferences;
Editor sharedPreferencesEditor;
CheckBox cbRememberMe;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.login_activity);
//before showing login, check if there is userpreference value set and if it is valid still
if (sharedPreferences.contains(USER_SHAREDPREFERENCE_KEY)){
String cachedProfile = sharedPreferences.getString(USER_SHAREDPREFERENCE_KEY, "");
if(!cachedProfile.trim().isEmpty()){
Log.d(TAG, "Cached User \n"+cachedProfile);
//check validity
long now = (new Date()).getTime();
long rememberUntil = sharedPreferences.getLong(USER_SHAREDPREFERENCE_VALIDITY_KEY, 0);
if(rememberUntil > now){
Log.d(TAG, "Cached User Still Valid Until "+(new Date(rememberUntil)));
//Here you could use libraries like Gson to convert the cachedProfile string into a POJO
//we can show the main activity, and then close the current one so that if the user clicks the back button, does not come back to the login activity
showMyMainActivity();
finish();
}
else{
Log.d(TAG, "Cached User EXPIRED -was only Valid Until "+(new Date(rememberUntil)));
//here the user's cached credentials have expired - we prompt the user to re-authenticate
}
}
}
cbRememberMe = (CheckBox)findViewById(R.id.chRememberMe);
Button loginButton = (Button) findViewById(R.id.loginBtn);
loginButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try{
EditText username = (EditText) findViewById(R.id.user_name);
EditText password = (EditText) findViewById(R.id.pass_word);
if (username.getText().toString().trim().isEmpty()
|| password.getText().toString().trim().isEmpty()) {
if (username.getText().toString().trim().isEmpty()) {
username.setError("Username cannot be empty");
}
if (password.getText().toString().trim().isEmpty()) {
password.setError("Password cannot be empty");
}
} else {
String u_name = username.getText().toString().trim();
String p_word = password.getText().toString().trim();
sendLoginRequest(u_name, p_word);
}
}
catch(Exception e){ Log.e(TAG, "Error while processing Login-Button Click", e);}
//do stuff
}
});
}
/**
* Helper method to effect login request
* @param username - username of the person trying to login
* @param password - password to authenticate
*/
private void sendLoginRequest(final String username, final String password) {
RequestQueue queue = Volley.newRequestQueue(this);
JSONObject joLoginRequest = new JSONObject();
try {
joLoginRequest.put("username", username);
joLoginRequest.put("password", password);
LoginJsonRequest jsObjRequest = new LoginJsonRequest(
Request.Method.POST, impulseLoginURL, joLoginRequest,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
processLoginSuccessful(response, password);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
try {
Toast.makeText(LoginActivity.this, "Wrong Username or Password. Please Try again", Toast.LENGTH_LONG).show();
Log.w(TAG, "There was an error processing the Login Request. Error is "+error);
}
catch (NullPointerException err) {Log.e(TAG, err.getLocalizedMessage(), err);}
}
});
queue.add(jsObjRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* Helper method to process the login response from Server
* @param results
*/
private void processLoginSuccessful(JSONObject loginResponse, String successfulPassword) {
Log.i(TAG, "Got Login Response: \n"+loginResponse.toString());
MyUser loggedInUser = MyUser.asMyUser(loginResponse.toString());
try {
if (loginResponse != null) {
loggedInUser.setPassword(successfulPassword);
if(cbRememberMe.isChecked()){
sharedPreferencesEditor.putString(USER_SHAREDPREFERENCE_KEY, loggedInUser.toString());
//time for which this login is valid
ong rememberUntil = (new Date()).getTime() + DEFAULT_REMEMBER_UNTIL;
sharedPreferencesEditor.putLong(USER_SHAREDPREFERENCE_VALIDITY_KEY, rememberUntil);
sharedPreferencesEditor.commit();
}
//now we can proceed to main activity...
showMyMainActivity();
finish();
} else {
Toast.makeText(LoginActivity.this, "Problem Processing Login Response from Server. Please try again.",Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
finally{
//just clear the entry fields
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment