Advertisement
Guest User

Untitled

a guest
May 9th, 2016
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.36 KB | None | 0 0
  1. package za.co.ishlema.blog.examples;
  2. /**
  3. * This is an example of implementing "remember me" login option using SharedPreferences in Android.
  4. * @author Ishmael Makitla,
  5. *
  6. * */
  7. public class LoginActivity extends Activity {
  8. private static final String TAG = LoginActivity.class.getSimpleName();
  9. public static final String USER_SHAREDPREFERENCE_KEY = "userPrefKey";
  10. public static final String USER_SHAREDPREFERENCE_VALIDITY_KEY = "valid";
  11.  
  12. //BY DEFAULT the app should remember the user (auto-login) for at most 5 days - unless if he logs out explicitly.
  13. public static final long DEFAULT_REMEMBER_UNTIL = (1000*60*60*24*5);
  14. //shared preferences
  15. SharedPreferences sharedPreferences;
  16. Editor sharedPreferencesEditor;
  17. CheckBox cbRememberMe;
  18.  
  19. @Override
  20. protected void onCreate(Bundle savedInstanceState) {
  21. super.onCreate(savedInstanceState);
  22. this.requestWindowFeature(Window.FEATURE_NO_TITLE);
  23. setContentView(R.layout.login_activity);
  24.  
  25. //before showing login, check if there is userpreference value set and if it is valid still
  26. if (sharedPreferences.contains(USER_SHAREDPREFERENCE_KEY)){
  27. String cachedProfile = sharedPreferences.getString(USER_SHAREDPREFERENCE_KEY, "");
  28. if(!cachedProfile.trim().isEmpty()){
  29. Log.d(TAG, "Cached User \n"+cachedProfile);
  30. //check validity
  31. long now = (new Date()).getTime();
  32. long rememberUntil = sharedPreferences.getLong(USER_SHAREDPREFERENCE_VALIDITY_KEY, 0);
  33. if(rememberUntil > now){
  34. Log.d(TAG, "Cached User Still Valid Until "+(new Date(rememberUntil)));
  35. //Here you could use libraries like Gson to convert the cachedProfile string into a POJO
  36. //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
  37. showMyMainActivity();
  38. finish();
  39. }
  40. else{
  41. Log.d(TAG, "Cached User EXPIRED -was only Valid Until "+(new Date(rememberUntil)));
  42. //here the user's cached credentials have expired - we prompt the user to re-authenticate
  43. }
  44. }
  45. }
  46.  
  47. cbRememberMe = (CheckBox)findViewById(R.id.chRememberMe);
  48. Button loginButton = (Button) findViewById(R.id.loginBtn);
  49.  
  50. loginButton.setOnClickListener(new View.OnClickListener() {
  51. public void onClick(View v) {
  52. try{
  53. EditText username = (EditText) findViewById(R.id.user_name);
  54. EditText password = (EditText) findViewById(R.id.pass_word);
  55. if (username.getText().toString().trim().isEmpty()
  56. || password.getText().toString().trim().isEmpty()) {
  57. if (username.getText().toString().trim().isEmpty()) {
  58. username.setError("Username cannot be empty");
  59. }
  60. if (password.getText().toString().trim().isEmpty()) {
  61. password.setError("Password cannot be empty");
  62. }
  63. } else {
  64. String u_name = username.getText().toString().trim();
  65. String p_word = password.getText().toString().trim();
  66. sendLoginRequest(u_name, p_word);
  67. }
  68. }
  69. catch(Exception e){ Log.e(TAG, "Error while processing Login-Button Click", e);}
  70. //do stuff
  71. }
  72. });
  73. }
  74.  
  75.  
  76. /**
  77. * Helper method to effect login request
  78. * @param username - username of the person trying to login
  79. * @param password - password to authenticate
  80. */
  81. private void sendLoginRequest(final String username, final String password) {
  82.  
  83. RequestQueue queue = Volley.newRequestQueue(this);
  84.  
  85. JSONObject joLoginRequest = new JSONObject();
  86. try {
  87. joLoginRequest.put("username", username);
  88. joLoginRequest.put("password", password);
  89.  
  90. LoginJsonRequest jsObjRequest = new LoginJsonRequest(
  91. Request.Method.POST, impulseLoginURL, joLoginRequest,
  92. new Response.Listener<JSONObject>() {
  93. @Override
  94. public void onResponse(JSONObject response) {
  95. processLoginSuccessful(response, password);
  96. }
  97. }, new Response.ErrorListener() {
  98. @Override
  99. public void onErrorResponse(VolleyError error) {
  100. try {
  101. Toast.makeText(LoginActivity.this, "Wrong Username or Password. Please Try again", Toast.LENGTH_LONG).show();
  102. Log.w(TAG, "There was an error processing the Login Request. Error is "+error);
  103. }
  104. catch (NullPointerException err) {Log.e(TAG, err.getLocalizedMessage(), err);}
  105. }
  106. });
  107. queue.add(jsObjRequest);
  108.  
  109. } catch (JSONException e) {
  110. e.printStackTrace();
  111. }
  112. }
  113.  
  114.  
  115. /**
  116. * Helper method to process the login response from Server
  117. * @param results
  118. */
  119. private void processLoginSuccessful(JSONObject loginResponse, String successfulPassword) {
  120. Log.i(TAG, "Got Login Response: \n"+loginResponse.toString());
  121. try {
  122.  
  123. if (loginResponse != null) {
  124. loggedInUser.setPassword(successfulPassword);
  125. if(cbRememberMe.isChecked()){
  126. sharedPreferencesEditor.putString(USER_SHAREDPREFERENCE_KEY, loggedInUser.toString());
  127. //time for which this login is valid
  128. long rememberUntil = (new Date()).getTime() + DEFAULT_REMEMBER_UNTIL;
  129. sharedPreferencesEditor.putLong(USER_SHAREDPREFERENCE_VALIDITY_KEY, rememberUntil);
  130. sharedPreferencesEditor.commit();
  131. }
  132. //now we can proceed to main activity...
  133. showMyMainActivity();
  134. finish();
  135. } else {
  136. Toast.makeText(LoginActivity.this, "Problem Processing Login Response from Server. Please try again.",Toast.LENGTH_LONG).show();
  137. }
  138.  
  139. } catch (Exception e) {
  140. e.printStackTrace();
  141. }
  142. finally{
  143. //just clear the entry fields
  144. }
  145. }
  146.  
  147. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement